אונטערשייד צווישן ווערסיעס פון "יחידה:תבנית מידע"

פון המכלול
קפיצה לניווט קפיצה לחיפוש
(מ'האט געשמועסט אז עכ"פ ביי פאראמעטערן וכדו' וועלכע ווערן נישט געצייגט צום ליינער וועט מען לאזן די אריגינעלע נעמען, און נאר צולייגן די אידישע. ביטע זיך האלטן דערצו.)
(אפדעיט)
 
(4 צווישנדיגע ווערסיעס פונעם זעלבן באַניצער נישט געוויזן)
שורה 355: שורה 355:
if hasData then
if hasData then
if options['formatter'] then
res = options['formatter'](res)
end
local link = mw.title.makeTitle( 0, entityId, propertyName, 'wikidata' ):fullUrl('uselang=he')
local link = mw.title.makeTitle( 0, entityId, propertyName, 'wikidata' ):fullUrl('uselang=he')
res = res .. mw.ustring.format(' [[File:Blue pencil RTL.svg|15px|link=%s|עריכת הנתון בוויקינתונים]]', link)
res = res .. mw.ustring.format(' [[File:Blue pencil RTL.svg|15px|link=%s|עריכת הנתון בוויקינתונים]]', link)
שורה 400: שורה 404:
local filterFunc = mw.ustring.match(templateParams[missingParam..'-ויקינתונים-סינון'],'filter[a-zA-Z]+')
local filterFunc = mw.ustring.match(templateParams[missingParam..'-ויקינתונים-סינון'],'filter[a-zA-Z]+')
wikidataOptions['filter'] = require(moduleTitle)[filterFunc]
wikidataOptions['filter'] = require(moduleTitle)[filterFunc]
end
if templateParams[missingParam..'-ויקינתונים-עיצוב'] and mw.ustring.match(templateParams[missingParam..'-ויקינתונים-עיצוב'], '[a-zA-Z]+') then
local moduleTitle = mw.ustring.match( frame:getParent():getTitle(), 'מוסטער:(.+)' )
moduleTitle = mw.ustring.format('יחידה:%s', moduleTitle)
local formatFunc = templateParams[missingParam..'-ויקינתונים-עיצוב']
wikidataOptions['formatter'] = require(moduleTitle)[formatFunc]
end
end
שורה 413: שורה 424:
wikidataOptions['img-width'] = templateParams[missingParam..'-ויקינתונים-תמונה-גודל']
wikidataOptions['img-width'] = templateParams[missingParam..'-ויקינתונים-תמונה-גודל']
end
end
if templateParams[missingParam..'-ויקינתונים'] then
if templateParams[missingParam..'-ויקינתונים'] then
if templateParams[missingParam..'-ויקינתונים-יחידה'] then
if templateParams[missingParam..'-ויקינתונים-יחידה'] then
שורה 430: שורה 442:
wikidataOptions['seperator'] = templateParams[missingParam..'-ויקינתונים-מרובה-הפרדה']
wikidataOptions['seperator'] = templateParams[missingParam..'-ויקינתונים-מרובה-הפרדה']
wikidataOptions['sort'] = { templateParams[missingParam..'-ויקינתונים-מרובה-מיון'] } or nil
wikidataOptions['sort'] = { templateParams[missingParam..'-ויקינתונים-מרובה-מיון'] } or nil
if templateParams[missingParam..'-ויקינתונים-מרובה-מיון-יורד'] then
wikidataOptions['sort-order'] = 'desc'
end
paramsData = {}
paramsData = {}
-- split multiple params to include all of them (e.g: "P1,P2")
-- split multiple params to include all of them (e.g: "P1,P2")
שורה 458: שורה 473:
local wikidataParamValue = propertyLink.getLabel(templateParams[missingParam..'-ויקינתונים-פשוט'], entityId)
local wikidataParamValue = propertyLink.getLabel(templateParams[missingParam..'-ויקינתונים-פשוט'], entityId)
if wikidataParamValue and #wikidataParamValue>0 then
if wikidataParamValue and #wikidataParamValue>0 then
templateArg.data = frame:preprocess(mw.ustring.gsub(templateArg.data, '\{\{\{('..missingParam..')\}\}\}', wikidataParamValue))
templateArg.data = frame:preprocess(mw.ustring.gsub(templateArg.data, '{{{('..missingParam..')}}}', wikidataParamValue))
inWikidata = true
inWikidata = true
end
end
שורה 519: שורה 534:
]]
]]
function standardTitle(templateArgs, isSubTemplate, entityId)
function standardTitle(templateArgs, isSubTemplate, entityId)
local name = templateArgs['שם']
local name = templateArgs['שם'] or templateArgs['נאמען']
if name=='-' then return name end --  
if name=='-' then return name end --  
if isSubTemplate then return name or '' end
if isSubTemplate then return name or '' end
שורה 538: שורה 553:
if #propertyVals == 0 then propertyVals = mw.wikibase.getBestStatements(entityId, 'P1559') end
if #propertyVals == 0 then propertyVals = mw.wikibase.getBestStatements(entityId, 'P1559') end
if #propertyVals > 0 then
if #propertyVals > 0 then
local propValue = propertyVals[1].mainsnak and propertyVals[1].mainsnak.datavalue
for _,propertyVal in pairs(propertyVals) do
if  propValue and propValue.value and propValue.value.text and propValue.value.text~=name then
local propValue = propertyVal.mainsnak and propertyVal.mainsnak.datavalue
originName = mw.ustring.format('<span lang="%s" title="%s">%s</span>', propValue.value.language,  
-- by convention we pick single origin name
        mw.language.fetchLanguageName( propValue.value.language , 'he'), propValue.value.text)
if  propValue and propValue.value and propValue.value.text and propValue.value.text~=name and not originName then
    end
originName = mw.ustring.format('<span lang="%s" title="%s">%s</span>', propValue.value.language,  
        mw.language.fetchLanguageName( propValue.value.language , 'he'), propValue.value.text)
    end
end
end
end
end
end
if originName and #originName and originName~=name then
if originName and #originName and originName~=name then
name = name..'<br>'..originName
name = name..'<br>'..originName
שורה 560: שורה 577:
local templateStructure = {}
local templateStructure = {}
args.subtemplate = frame.args['תת-תבנית']
args.subtemplate = frame.args['תת-תבנית']
args.entityId = templateArgs['qid'] or templateParams['qid']
if (templateArgs['qid'] ~= nil and templateArgs['qid'] ~= '') then
args.entityId = templateArgs['qid']
else
args.entityId = templateParams['qid']
end
-- disable wikidata fetching
-- disable wikidata fetching
if args.entityId == '' or args.entityId == '-' then args.entityId = nil end
if args.entityId == '' or args.entityId == '-' then args.entityId = nil end
שורה 567: שורה 588:
args.titlestyle = templateParams['כותרת תבנית-עיצוב']
args.titlestyle = templateParams['כותרת תבנית-עיצוב']
args.titleclass = templateParams['כותרת תבנית-מחלקה']
args.titleclass = templateParams['כותרת תבנית-מחלקה']
args.subtitle = templateParams['תת כותרת תבנית']
args.subtitle = templateParams['תת-כותרת תבנית']
args.subtitlestyle = templateParams['תת כותרת תבנית-עיצוב']
args.subtitlestyle = templateParams['תת-כותרת תבנית-עיצוב']
args.subtitleclass = templateParams['תת כותרת תבנית-מחלקה']
args.subtitleclass = templateParams['תת-כותרת תבנית-מחלקה']
args.rightImageDesc = templateParams['כיתוב ימין']
args.rightImageDesc = templateParams['כיתוב ימין']
שורה 575: שורה 596:
valueArg=templateParams['תמונה ימין'],
valueArg=templateParams['תמונה ימין'],
wikidataArg=templateParams['תמונה ימין-ויקינתונים'],
wikidataArg=templateParams['תמונה ימין-ויקינתונים'],
width='100x80',  
width=templateParams['תמונה ימין-גודל'] or '100x80',  
imgDesc=args.rightImageDesc,
imgDesc=args.rightImageDesc,
args=args
args=args
שורה 584: שורה 605:
valueArg=templateParams['תמונה שמאל'],
valueArg=templateParams['תמונה שמאל'],
wikidataArg=templateParams['תמונה שמאל-ויקינתונים'],
wikidataArg=templateParams['תמונה שמאל-ויקינתונים'],
width='100x80',  
width=templateParams['תמונה שמאל-גודל'] or '100x80',  
imgDesc=args.leftImageDesc,
imgDesc=args.leftImageDesc,
args=args
args=args
שורה 592: שורה 613:
if templateParams['תמונה ללא שאיבה אוטומטית'] ==  'כן' then
if templateParams['תמונה ללא שאיבה אוטומטית'] ==  'כן' then
args.image, args.imageDesc = getValueOrWikidataImage{
args.image, args.imageDesc = getValueOrWikidataImage{
valueArg=templateParams['תמונה'],
valueArg=templateParams['תמונה'] or templateParams['בילד'],
wikidataArg=templateParams['תמונה-ויקינתונים'],
wikidataArg=templateParams['תמונה-ויקינתונים'],
width=templateParams['תמונה-גודל'] or '220',
width=templateParams['תמונה-גודל'] or '220',
שורה 758: שורה 779:
else
else
-- otherwise if the template isn't full or if there is a Wikidata-beats tag - them try to use wikidata to fill it
-- otherwise if the template isn't full or if there is a Wikidata-beats tag - them try to use wikidata to fill it
local m = mw.ustring.match(v.data, '\{\{\{(.-)\}\}\}')
local m = mw.ustring.match(v.data, '{{{(.-)}}}')
if v.label and templateParams[v.label..'-ויקינתונים-גובר'] then
if v.label and templateParams[v.label..'-ויקינתונים-גובר'] then
m = templateParams[v.label..'-ויקינתונים-גובר']
m = templateParams[v.label..'-ויקינתונים-גובר']
שורה 803: שורה 824:
-- use wikidata in title
-- use wikidata in title
if args.title then
if args.title then
local m = mw.ustring.match(args.title, '\{\{\{(.-)\|?\}\}\}')  
local m = mw.ustring.match(args.title, '{{{(.-)|(?)}}}')  
if m then
if m then
local inWikidata = false
local inWikidata = false
שורה 815: שורה 836:
local wikidataParamValue = propertyLink.getLabel(templateParams[m..'-ויקינתונים-פשוט'])
local wikidataParamValue = propertyLink.getLabel(templateParams[m..'-ויקינתונים-פשוט'])
if wikidataParamValue then
if wikidataParamValue then
args.title = frame:preprocess(mw.ustring.gsub(args.title, '\{\{\{('..m..')\|?\}\}\}', wikidataParamValue))
args.title = frame:preprocess(mw.ustring.gsub(args.title, '{{{('..m..')|?}}}', wikidataParamValue))
end
end
end
end

יעצטיגע רעוויזיע זינט 02:40, 23 פעברואר 2025

מען קען שאפן דאקומענטאציע פאר דעם מאדול ביי יחידה:תבנית מידע/דאק

local propertyLink = require('Module:PropertyLink')
local WikidataCrossValidation = require('Module:WikidataCrossValidation')
local Infobox = {}
function Infobox:new()
	local o = {
		args={},
		templateStructure={},
		isSelfUse=false,
		autoDocumentation=false,
		wikidataCats= {},
		root = mw.html.create('table')
	}
	setmetatable(o, self)
	self.__index = self
	
	return o
end

function Infobox:render()
	if self.isSelfUse then
		local templateDocumentation=''
		for k,v in pairs(self.templateParams) do
			if mw.ustring.match( k, '-ויקינתונים') then
				templateDocumentation = templateDocumentation .. '[[קאַטעגאָריע:תבניות מידע שמשתמשות בוויקינתונים]]'
				break
			end
		end
		if self.autoDocumentation then
			templateDocumentation = templateDocumentation .. self:_generateDocumentation()			
		end
		return self:renderInfobox() .. templateDocumentation
	end

	return self:renderInfobox() .. table.concat(self.wikidataCats, '')
end
 
--[[
Generate auto documentation for template.
]]
function Infobox:_generateDocumentation() 
	local labelDataPrefix = 'תווית-מידע'
	
	local parameters = {}
	for k,v in pairs(self.templateParams) do
		if mw.ustring.match( tostring(k),'תווית%-מידע%d' )  then
			table.insert(parameters, '"'..string.gsub(v, '"', '\\"')..'":'..'{ "description": ""}')
		else
			for mm in mw.ustring.gmatch( tostring(v),'%{%{%{(.-)[%}|]') do
				table.insert(parameters, '"'..string.gsub(mm, '"', '\\"')..'":'..'{ "description": ""}')
			end
		end
		
	end
	local templateDoc = '{ "params": { '..table.concat(parameters,'\n,')..'}}'
	return frame:extensionTag( 'templatedata', templateDoc )
end

--[[ 
Renders the infobox title
]]
function Infobox:renderTitle()
	-- renders the title
	local  titleCaption = self.root
        :tag('caption')
        	:attr('dir', 'auto')
            :addClass(self.args.titleclass)
            :cssText(self.args.titlestyle)
            :wikitext(self.args.title)

	if self.args.subtitle and  self.args.subtitle~=nil and #(self.args.subtitle)>0 then
		local row = self.root:tag('tr')
				:tag('th')
				:attr('colspan', 2)
				:css('text-align','center')
				:cssText(self.args.subtitlestyle)
				:addClass(self.args.subtitleclass)
				:wikitext(self.args.subtitle)
	end
	return self.titleCaption
end

--[[ 
Renders the right/left images (possibly 1/2/none of them available) and the main image
]]
function Infobox:renderImages()
	-- render right an left images 
	self.args.rightImage = self.args.rightImage~=nil and #(self.args.rightImage)>0 and self.args.rightImage
	self.args.leftImage = self.args.leftImage~=nil and #(self.args.leftImage)>0 and self.args.leftImage
	
	if self.args.rightImage or self.args.leftImage then
		if self.args.rightImage and self.args.rightImageDesc~=nil and #(self.args.rightImageDesc)>0 then
			self.args.rightImage = self.args.rightImage..'<div>' .. self.args.rightImageDesc .. '</div>'
		end
		if self.args.leftImage and self.args.leftImageDesc~=nil and #(self.args.leftImageDesc)>0 then
			self.args.leftImage = self.args.leftImage .. '<div>' .. self.args.leftImageDesc .. '</div>'
		end
		local row = self.root:tag('tr')
						:tag('td')
						:attr('colspan', 2)
						:css('text-align','center')
		if self.args.rightImage and self.args.leftImage then
			row:tag('table')
				:css('width','100%')
				:css('display','table')
				:tag('tr')
					:tag('td')
						:css('width','50%')
						:css('vertical-align','middle')
						:css('text-align','center')
						:wikitext(self.args.rightImage)
					:tag('td')
						:css('width','50%')
						:css('vertical-align','middle')
						:css('text-align','center')
						:wikitext(self.args.leftImage)
					:done()
		else
			row:wikitext(self.args.leftImage or self.args.rightImage)
		end
	end
	-- render the main image
	if self.args.image then
		self.root:tag('tr')
			:tag('td')
			:attr('colspan', 2)
			:css('text-align','center')
			:wikitext(self.args.image)
		if self.args.imageDesc and #self.args.imageDesc>0 then
			self.root:tag('tr')
			:tag('td')
			:attr('colspan', 2)
			:addClass('thumbcaption')
			:addClass('borderless')
			:css('text-align','center')
			:wikitext(self.args.imageDesc)
		end
		
	end
end

--[[ 
Adds edit links for easier editing of the template. If the template use data from wikidata it also adds edit link in Wikidata
]]
function Infobox:renderEditLinks()
end

--[[ 
Adds a styled row to the table
]]
function Infobox:addRow(rowArgs)
    -- Adds a row to the infobox, with either a header cell
    -- or a label/data cell combination.
    if rowArgs.header then
        self.root
            :tag('tr')
                :addClass(rowArgs.rowclass)
                :cssText(self.args.rowsstyle)
                :cssText(rowArgs.rowstyle)
                :attr('id', rowArgs.rowid)
                :tag('th')
                    :attr('colspan', 2)
                    :attr('id', rowArgs.headerid)
                    :addClass(rowArgs.class)
                    :addClass(self.args.headerclass)
                    :css('text-align', 'center')
                    :cssText(self.args.headerstyle)
                    :cssText(rowArgs.headerstyle)
                    :newline()
                    :wikitext(rowArgs.data)
    elseif rowArgs.data and #(rowArgs.data) > 0 then
        local row = self.root:tag('tr')
        row:addClass(rowArgs.rowclass)
           :cssText(self.args.rowsstyle)
           :cssText(rowArgs.rowstyle)
           :attr('id', rowArgs.rowid)
        if rowArgs.label then
            row
                :tag('th')
                    :attr('scope', 'row')
                    :addClass('infobox-label')
                    :attr('id', rowArgs.labelid)
                    :cssText(self.args.labelstyle)
                    :cssText(rowArgs.labelstyle)
                    :newline()
                    :wikitext(rowArgs.label)
                    :done()
        end
 
        local dataCell = row:tag('td')
        if not rowArgs.label then 
            dataCell
                :attr('colspan', 2)
            if not rowArgs.datastyle then 
                dataCell:css('text-align', 'center') 
            end
        end
        dataCell
            :attr('id', rowArgs.dataid)
            :addClass(rowArgs.class)
            :cssText(self.args.datastyle)
            :cssText(rowArgs.datastyle)
            :newline()
            :wikitext(rowArgs.data)
    end
end


 --[[ 
This function removes redundent keys from templateStructure: nil entries and header entries with no data
]]
function Infobox:removeEmptyHeaders()
 	local lastHeaderIndex=nil

 	local hasImage = (self.args.image~=nil and #self.args.image>0) 
 	hasImage = hasImage or (self.args.rightImage~=nil and #self.args.rightImage>0)
 	hasImage = hasImage or (self.args.leftImage~=nil and #self.args.leftImage>0) 

	local removeFirstHeader = nil
	if self.args.removeFirstHeader~=nil then
		removeFirstHeader = (not hasImage) and self.args.removeFirstHeader -- remove the first header if there are no images & the first header is generic
	else
		removeFirstHeader = (not hasImage)-- default, remove the first header if there are no images
	end

 	local tempTemplateStructure = {}
 	for i,v in pairs(self.templateStructure) do
  		if v~=nil then
 			if v.header then
 				lastHeaderIndex = i
 			else
 				if lastHeaderIndex then
 					if not removeFirstHeader then
 						-- skip headers that are only spaces/nowiki - marking structure seperation
						local headerData =mw.text.unstripNoWiki( self.templateStructure[lastHeaderIndex].data ) 
						local headerDataNoSpace = mw.ustring.gsub(headerData, "%s", "")
						if #headerDataNoSpace >0 then
 							table.insert(tempTemplateStructure, self.templateStructure[lastHeaderIndex])
						end 
 					end
 					lastHeaderIndex = nil
 				end
 				removeFirstHeader = false
 				table.insert(tempTemplateStructure, v)
 			end
 		end
 	end
 	self.templateStructure=tempTemplateStructure
end

--[[ 
This function builds the infobox table using structure templateStructure and args
]]
function Infobox:renderInfobox()
	self:removeEmptyHeaders()
	
	-- sub infobox
	if self.args.subtemplate then
		self.root:cssText(self.args.tablestyle):css('width', '100%'):css('line-height', '1.4em')
	else
		self.root:addClass('infobox'):cssText(self.args.tablestyle)
	end
	if self.args.tableclass then
		self.root:addClass(self.args.tableclass)
	end
	if self.args.title ~='-' then
		self:renderTitle()
	end
	
	if not self.args.subtemplate then
		self:renderImages()
	end
	
	local infobox_rows={}
	for k,v in pairs(self.templateStructure) do
		self:addRow(v)
	end
	if self.args.title ~= '-' then
		self:renderEditLinks()
	end
	
	return tostring(self.root)
end

--[[ 
This function adds image using valueArg, or if not specified by the user tries to get image from wikidata using property
]]
function getValueOrWikidataImage(args)
	valueArg = args.valueArg
	if valueArg and #valueArg>0 then 
		if valueArg == '-' then
			return nil
		else
			-- wrap with wikisyntax if only filename provided. avoid that in case of tags or wikisyntaxed files
			if	not mw.ustring.match(valueArg, '%[%[') and  
			    not  mw.ustring.match(valueArg, '<') then
			   	local imgSuffix = '|'..args.width .. 'px'
			   	if args.imgDesc~=nil and #args.imgDesc>0 then
			   		imgSuffix = imgSuffix .. '|' .. args.imgDesc
			   	end
			   	imgSuffix = imgSuffix .. ']]'
				if mw.ustring.match(valueArg, '^[Ff]ile:') or 
				mw.ustring.match(valueArg, '^[Ii]mage:') or
				mw.ustring.match(valueArg, '^קובץ:') or
				mw.ustring.match(valueArg, '^טעקע:') or
				mw.ustring.match(valueArg, '^תמונה:') then
					valueArg = '[[' .. valueArg .. imgSuffix
				else
					valueArg = '[[File:' .. valueArg .. imgSuffix
				end
			elseif args.imgDesc~=nil and #args.imgDesc>0 and not mw.ustring.match(args.imgDesc, '%[%[קאַטעגאָריע:ערכים להחלפת תמונה בחופשית%]%]$') then
				if mw.ustring.match(valueArg, '^ *%[%[[Ff]ile:') or 
				mw.ustring.match(valueArg, '^ *%[%[[Ii]mage:') or
				mw.ustring.match(valueArg, '^ *%[%[קובץ:') or
				mw.ustring.match(valueArg, '^ *%[%[טעקע:') or
				mw.ustring.match(valueArg, '^ *%[%[תמונה:') then
					valueArg = mw.ustring.gsub(valueArg, "%]%]$", "")
					local imgSuffix = '|' .. args.imgDesc .. ']]'
					valueArg = valueArg .. imgSuffix
				end
			end
			return valueArg, args.imgDesc
		end
	end
	if args.wikidataArg and args.args.entityId~=nil then 
		args.args.usingWikidata = true
		return propertyLink.getImageLink(args.wikidataArg, args.width, nil, nil,nil, args.args.entityId)
	end
	return ''
	
end

--[[
Split category links from value, return tuple of whether data exists and maitainance cats in case no data exists
]]
function splitMaintainceCategory(value)
	local maintainceCats = nil
	local hasData =  #(mw.ustring.gsub(value, '%[%[קאַטעגאָריע:.-%]%]', ''))>0
	if not hasData then
		maintainceCats = value
	end
	return hasData, maintainceCats
end

function getPropertyByOptions( propertyName, entityId, options )
	if propertyName == nil or #propertyName == 0 then
		return nil
	end

	local res = propertyLink.getPropertyByOptions(propertyName, entityId, options)
	if (res==nil) or (#res == 0) then
		return nil
	end
	
	local hasData, maintainceCats = splitMaintainceCategory(res)
	
	if hasData then
		if options['formatter'] then
			res = options['formatter'](res)
		end

		local link = mw.title.makeTitle( 0, entityId, propertyName, 'wikidata' ):fullUrl('uselang=he')
		res = res .. mw.ustring.format(' [[File:Blue pencil RTL.svg|15px|link=%s|עריכת הנתון בוויקינתונים]]', link)
	end
	return res
end

--[[
Filters statements to statements with existing links only
]]
function filterExists( propertyVals )
	local tempVals = {}
    for i, property in ipairs(propertyVals) do
    	local propValue = property.mainsnak and property.mainsnak.datavalue
    	if propValue and propValue.value then
	    	local linkTarget = mw.wikibase.sitelink( propValue.value['id'] )
			if linkTarget then
				table.insert(tempVals, property)
			end
		end
	end
	return tempVals
end

--[[
This function fills missing parameter using wikidata
]]
function fillMissingParamFromWikidata(missingParam, templateParams, templateArg, entityId, frame)
	local inWikidata = false
	local hasData=false
	local maintainceCats = nil
	local includeWikidataRef = frame and frame:getParent()
	if entityId == nil then return inWikidata, maintainceCats end -- early terminate
	includeWikidataRef = includeWikidataRef and includeWikidataRef.args and includeWikidataRef.args['ויקינתונים-מקורות'] == 'כן'
	
	local wikidataOptions = {
		['entity-gender-aware'] =  templateParams[missingParam..'-ויקינתונים-מגדר'] == 'כן',
		['source'] = includeWikidataRef
	}
	if templateParams[missingParam..'-ויקינתונים-סינון'] == 'קיים' then
		wikidataOptions['filter'] = filterExists
	elseif templateParams[missingParam..'-ויקינתונים-סינון'] and mw.ustring.match(templateParams[missingParam..'-ויקינתונים-סינון'], 'filter[a-zA-Z]+') then
		local moduleTitle = mw.ustring.match( frame:getParent():getTitle(), 'מוסטער:(.+)' )
		moduleTitle = mw.ustring.format('יחידה:%s', moduleTitle)
		local filterFunc = mw.ustring.match(templateParams[missingParam..'-ויקינתונים-סינון'],'filter[a-zA-Z]+')
		wikidataOptions['filter'] = require(moduleTitle)[filterFunc]
	end

	if templateParams[missingParam..'-ויקינתונים-עיצוב'] and mw.ustring.match(templateParams[missingParam..'-ויקינתונים-עיצוב'], '[a-zA-Z]+') then
		local moduleTitle = mw.ustring.match( frame:getParent():getTitle(), 'מוסטער:(.+)' )
		moduleTitle = mw.ustring.format('יחידה:%s', moduleTitle)
		local formatFunc = templateParams[missingParam..'-ויקינתונים-עיצוב']
		wikidataOptions['formatter'] = require(moduleTitle)[formatFunc]
	end
	
	if templateParams[missingParam..'-ויקינתונים-פרטים']~=nil then
		wikidataOptions['qualifiers'] = {}
		wikidataOptions['qualifiers-sep'] = templateParams[missingParam..'-ויקינתונים-פרטים-הפרדה'] or nil
		for v in string.gmatch(templateParams[missingParam..'-ויקינתונים-פרטים'], "[^,%s]+") do
    		table.insert(wikidataOptions['qualifiers'], v)
		end
		wikidataOptions['default-value'] = templateParams[missingParam..'-ויקינתונים-פרטים-ברירת מחדל'] or nil
	end
	if templateParams[missingParam..'-ויקינתונים-תמונה-גודל']~=nil then
		wikidataOptions['img-width'] = templateParams[missingParam..'-ויקינתונים-תמונה-גודל']
	end

	if templateParams[missingParam..'-ויקינתונים'] then
		if templateParams[missingParam..'-ויקינתונים-יחידה'] then
			templateArg.data = require('Module:Convert').convert(mw.getCurrentFrame():newChild{ args = {
				['input'] = templateParams[missingParam..'-ויקינתונים'],
				[2] = templateParams[missingParam..'-ויקינתונים-יחידה'],
				['disp'] = 'out',
				['qid'] = entityId,
				['abbr']='off'
			} }:newChild{})
		else
			templateArg.data = getPropertyByOptions(templateParams[missingParam..'-ויקינתונים'], entityId,  wikidataOptions) or nil
		end
		inWikidata = templateArg.data and #(templateArg.data)>0
	elseif templateParams[missingParam..'-ויקינתונים-מרובה'] then
		wikidataOptions['allowMulti'] = true
		wikidataOptions['seperator'] = templateParams[missingParam..'-ויקינתונים-מרובה-הפרדה']
		wikidataOptions['sort'] = { templateParams[missingParam..'-ויקינתונים-מרובה-מיון'] } or nil
		if templateParams[missingParam..'-ויקינתונים-מרובה-מיון-יורד'] then
			wikidataOptions['sort-order'] = 'desc'
		end
		paramsData = {}
		-- split multiple params to include all of them (e.g: "P1,P2")
		for paramToFetch in string.gmatch(templateParams[missingParam..'-ויקינתונים-מרובה'], '([^,]+)') do
			-- split optional params to include ONLY the first one of them (e.g: "P1/P2")
			for optionalParam in string.gmatch(paramToFetch, '([^/]+)') do
				if (string.sub(optionalParam, 1, 1) == 'P' or string.sub(optionalParam, 1, 1) == 'Q') then
					if getPropertyByOptions(optionalParam, entityId,  wikidataOptions) then
						table.insert(paramsData, getPropertyByOptions(optionalParam, entityId,  wikidataOptions) or nil)
						-- found one of the optionals - stop the loop
						break
					end
				else
					-- one of the optionals is static data - take it and stop the loop
					table.insert(paramsData, optionalParam)
					break
				end
			end
		end
		if wikidataOptions['seperator'] == '*' and #paramsData>1 then
			templateArg.data = '*' .. table.concat( paramsData, '\n*' )
		else
			templateArg.data = table.concat(paramsData, wikidataOptions['seperator'])
		end
		inWikidata = templateArg.data and #(templateArg.data)>0
	elseif templateParams[missingParam..'-ויקינתונים-פשוט'] then
		-- use data should be taken from wikidata and link must not be added
		local wikidataParamValue = propertyLink.getLabel(templateParams[missingParam..'-ויקינתונים-פשוט'], entityId)
		if wikidataParamValue and #wikidataParamValue>0 then
			templateArg.data = frame:preprocess(mw.ustring.gsub(templateArg.data, '{{{('..missingParam..')}}}', wikidataParamValue))
			inWikidata = true
		end
	-- special cases
	elseif missingParam == 'קואורדינטות' then
		
		templateArg.data = propertyLink.getPropertyByOptions('P625', entityId, {['coord-display'] = templateParams['קואורדינטות-תצוגה'] or 'title,inline' })
		inWikidata = templateArg.data and #(templateArg.data)>0
	elseif  missingParam == 'מפה' and templateParams['מפה-זום'] then
		inWikidata = (#mw.wikibase.getBestStatements(entityId, 'P625'))>0
		if inWikidata then
			local defaultZoom = templateParams['מפה-זום']
			templateArg.data = frame:expandTemplate{ title = 'מפה דינמית', args = { 
				['יישור'] = 'center', 
				['זום ברירת מחדל'] = defaultZoom,
				['פריטים'] = entityId
			} }
		end
	end
	if inWikidata then
		hasData, maintainceCats = splitMaintainceCategory(templateArg.data)
		if not hasData then
			inWikidata = false
			maintainceCats = maintainceCats
		end
	end

	return inWikidata, maintainceCats
end

--[[
This function fills missing parameter using wikidata
]]
function crossValidateWikidata(missingParam, templateParams, templateArg, frame, entityId)
	local matching = nil
	local propertyName

	if entityId == nil or missingParam==nil then
		return nil
	end
	if templateParams[missingParam..'-ויקינתונים'] then
		propertyName = templateParams[missingParam..'-ויקינתונים']
		matching = WikidataCrossValidation.crossValidate(templateArg, propertyName, entityId)
	elseif templateParams[missingParam..'-ויקינתונים-פשוט'] then
		propertyName = templateParams[missingParam..'-ויקינתונים-פשוט']
		matching = WikidataCrossValidation.crossValidate(templateArg, propertyName, entityId)
	elseif templateParams[missingParam..'-ויקינתונים-מרובה'] then
		local genderAware = templateParams[missingParam..'-ויקינתונים-מגדר'] == 'כן'
		propertyName =  templateParams[missingParam..'-ויקינתונים-מרובה']
		matching = WikidataCrossValidation.crossValidate(templateArg, propertyName, entityId)
	end
	
	if matching then
		return WikidataCrossValidation.maintainceCategory(matching, propertyName)
	end
end

--[[
If template doesn't specify title parameter, the default is name (fallback by title) + origin name (fallback by wikidata)
]]
function standardTitle(templateArgs, isSubTemplate, entityId)
	local name = templateArgs['שם'] or templateArgs['נאמען']
	if name=='-' then return name end -- 
	if isSubTemplate then return name or '' end
	
	if not name or #name==0 then --fallback to title
		name = mw.title.getCurrentTitle().text
    	name = mw.ustring.gsub(name, " *[(].*[)]","")
	end
	
	local originName = templateArgs['שם בשפת המקור']
	if originName == '-' then 
		originName = ''
	else
		-- use wikidata as fallback
		if (not originName or #originName==0) and entityId~=nil then 
			local propertyVals = mw.wikibase.getBestStatements(entityId, 'P1705')
			if #propertyVals == 0 then propertyVals = mw.wikibase.getBestStatements(entityId, 'P1476') end
			if #propertyVals == 0 then propertyVals = mw.wikibase.getBestStatements(entityId, 'P1559') end
			if #propertyVals > 0 then
				for _,propertyVal in pairs(propertyVals) do
					local propValue = propertyVal.mainsnak and propertyVal.mainsnak.datavalue
					-- by convention we pick single origin name
					if  propValue and propValue.value and propValue.value.text and propValue.value.text~=name and not originName then
						originName = mw.ustring.format('<span lang="%s" title="%s">%s</span>', propValue.value.language, 
	    											     mw.language.fetchLanguageName( propValue.value.language , 'he'), propValue.value.text)
	    			end
				end
			end
		end
		if originName and #originName and originName~=name then
			name = name..'<br>'..originName
		end
	end
	return name
end

function Infobox:parseArgs(frame)
	local DEFAULT_IMAGE_PROPERTY = 'P18'
	local templateParams =  frame.args
	local templateArgs = frame:getParent().args
	local args={}
	local templateStructure = {}
	args.subtemplate = frame.args['תת-תבנית']
	if (templateArgs['qid'] ~= nil and templateArgs['qid'] ~= '') then
		args.entityId = templateArgs['qid']
	else
		args.entityId = templateParams['qid']
	end
	-- disable wikidata fetching
	if args.entityId == '' or args.entityId == '-' then args.entityId = nil	end
	args.title = frame.args['כותרת תבנית'] or standardTitle(templateArgs, args.subtemplate, args.entityId)
	if args.title=='-' then args.subtemplate = true	end
	args.titlestyle = templateParams['כותרת תבנית-עיצוב']
	args.titleclass = templateParams['כותרת תבנית-מחלקה']
	args.subtitle = templateParams['תת-כותרת תבנית']
	args.subtitlestyle = templateParams['תת-כותרת תבנית-עיצוב']
	args.subtitleclass = templateParams['תת-כותרת תבנית-מחלקה']
	
	args.rightImageDesc = templateParams['כיתוב ימין']
	args.rightImage, args.rightImageDesc = getValueOrWikidataImage{
		valueArg=templateParams['תמונה ימין'],
		wikidataArg=templateParams['תמונה ימין-ויקינתונים'],
		width=templateParams['תמונה ימין-גודל'] or '100x80', 
		imgDesc=args.rightImageDesc,
		args=args
	}
	
	args.leftImageDesc = templateParams['כיתוב שמאל']
	args.leftImage, args.leftImageDesc = getValueOrWikidataImage{
		valueArg=templateParams['תמונה שמאל'],
		wikidataArg=templateParams['תמונה שמאל-ויקינתונים'],
		width=templateParams['תמונה שמאל-גודל'] or '100x80', 
		imgDesc=args.leftImageDesc,
		args=args
	}

	args.imageDesc = templateParams['קעפל'] or templateParams['כיתוב']
	if templateParams['תמונה ללא שאיבה אוטומטית'] ==  'כן' then
		args.image, args.imageDesc = getValueOrWikidataImage{
			valueArg=templateParams['תמונה'] or templateParams['בילד'],
			wikidataArg=templateParams['תמונה-ויקינתונים'],
			width=templateParams['תמונה-גודל'] or '220',
			imgDesc=args.imageDesc,
			args=args
		}
	else
		args.image, args.imageDesc = getValueOrWikidataImage{
			valueArg=templateParams['בילד'] or templateParams['תמונה'],
			wikidataArg=templateParams['תמונה-ויקינתונים'] or 'P18',
			width=templateParams['תמונה-גודל'] or '220',
			imgDesc=args.imageDesc,
			args=args
		}
	end

	args.removeFirstHeader = false-- default based on vote on 18/7/21
    -- explictly override the default
    if templateParams['כותרת כללית'] ==  'כן' then 
		args.removeFirstHeader = true
	elseif templateParams['כותרת כללית'] ==  'לא' then 
		args.removeFirstHeader = false
	end
	
	args.headerclass = templateParams['כותרת-מחלקה']
	args.headerstyle = templateParams['כותרת-עיצוב']
    args.rowsstyle = templateParams['שורה-עיצוב']
    args.labelstyle = templateParams['תווית-עיצוב']
    args.datastyle = templateParams['מידע-עיצוב']
	args.tablestyle = templateArgs['טבלה-עיצוב'] or templateParams['טבלה-עיצוב']
	args.tableclass = templateArgs['טבלה-מחלקה'] or templateParams['טבלה-מחלקה']
	local pageNs = mw.title.getCurrentTitle().namespace
	local subpageText = mw.title.getCurrentTitle().subpageText
	local isSelfUse = (pageNs==10 and subpageText ~= "תיעוד")
	self.autoDocumentation = templateParams['תיעוד-אוטומטי']

	local labelPrefix = 'תווית'
	local dataPrefix = 'מידע'
	local parameterDataPrefix = 'מידע-פרמטרי'
	local subheader = 'כותרת'
	local labelDataPrefix = 'תווית-מידע'
	local rowStylePrefix = 'עיצוב-שורה'
	local rowStyleClassPrefix = 'מחלקה-שורה'
	local styleSuffix = '-עיצוב'
	local explicitWikidata = '-ויקינתונים-מפורש'
	local k=0
	local processedParams = {['0']=1} -- param0 may be used by Lua, not be template
	local wikidataCats = {}
	for k,v in pairs(templateParams) do
		local i= string.match(k, '.-([0-9]+)$')
		if i and not (processedParams[i]) then
			indic = tonumber(i)
			processedParams[i]=1
			
			local subHeaderName = templateParams[subheader..i]
			if subHeaderName and #subHeaderName>0  then --subheader type
				table.insert(templateStructure, {header=1,data=subHeaderName,rowstyle=templateParams[rowStylePrefix..i], rowclass=templateParams[rowStyleClassPrefix..i], headerstyle=templateParams[subheader..i..styleSuffix], indic=indic})
			else
				local labelName = templateParams[labelPrefix..i]
				local dataTemplate = templateParams[dataPrefix..i] or templateParams[parameterDataPrefix..i]
				if dataTemplate then
					-- if parameter contains only category with no value, replace with with nil and add the value to maintaince category
					local hasData, maintainceCats = splitMaintainceCategory(dataTemplate)
					if maintainceCats and not hasData then
						table.insert(wikidataCats, maintainceCats)
						dataTemplate=nil
					end
				end
				if labelName and dataTemplate then
					if dataTemplate == templateParams[parameterDataPrefix..i] then
						local hasContent = templateArgs[dataTemplate] and #templateArgs[dataTemplate]>0
						-- + and use explicit wikidata replace the content with such if available from wikidata
						local isExplicitWikidataParam = templateParams[dataTemplate..explicitWikidata]
						local isExplicitWikidataEnabled = false 
						if isExplicitWikidataParam then
							isExplicitWikidataEnabled = templateArgs[dataTemplate]~=nil and mw.ustring.match(templateArgs[dataTemplate], '^ *+$')
						end
						local skipContent = false
					 	if hasContent and not isExplicitWikidataEnabled then
					 		dataTemplate = templateArgs[dataTemplate]
				 		else
							if isExplicitWikidataParam and not isExplicitWikidataEnabled then
								skipContent = true
							end
				 			dataTemplate = '{{{' ..dataTemplate.. '}}}'
					 	end
					 	if not skipContent then
					 		table.insert(templateStructure, {label=labelName, data=dataTemplate, rowstyle=templateParams[rowStylePrefix..i], rowclass=templateParams[rowStyleClassPrefix..i], datastyle=templateParams[dataPrefix..i..styleSuffix], 
							labelstyle=templateParams[labelPrefix..i..styleSuffix], indic=indic})
					 	end
					 else
					 	table.insert(templateStructure, {label=labelName, data=dataTemplate, rowstyle=templateParams[rowStylePrefix..i], rowclass=templateParams[rowStyleClassPrefix..i], datastyle=templateParams[dataPrefix..i..styleSuffix], 
						labelstyle=templateParams[labelPrefix..i..styleSuffix], indic=indic})
					end
				elseif labelName and not dataTemplate then
					--skip it. no only label [use subheader]
				elseif not labelName and dataTemplate then
					if dataTemplate == templateParams[parameterDataPrefix..i] then
						local hasContent = templateArgs[dataTemplate] and #templateArgs[dataTemplate]>0
						-- + and use explicit wikidata replace the content with such if available from wikidata
						local isExplicitWikidataParam = templateParams[dataTemplate..explicitWikidata]
						local isExplicitWikidataEnabled = false 
						if isExplicitWikidataParam then
							isExplicitWikidataEnabled = templateArgs[dataTemplate]~=nil and mw.ustring.match(templateArgs[dataTemplate], '^ *+$')
						end
						local skipContent = false
					 	if hasContent and not isExplicitWikidataEnabled then
					 		dataTemplate = templateArgs[dataTemplate]
				 		else
							if isExplicitWikidataParam and not isExplicitWikidataEnabled then
								skipContent = true
							end
				 			dataTemplate = '{{{' ..dataTemplate.. '}}}'
					 	end
					 	if not skipContent then
					 		table.insert(templateStructure, {data=dataTemplate, rowstyle=templateParams[rowStylePrefix..i], rowclass=templateParams[rowStyleClassPrefix..i], datastyle=templateParams[dataPrefix..i..styleSuffix], indic=indic})
					 	end
					 else
					 	table.insert(templateStructure, {data=dataTemplate, rowstyle=templateParams[rowStylePrefix..i], rowclass=templateParams[rowStyleClassPrefix..i], datastyle=templateParams[dataPrefix..i..styleSuffix], indic=indic})
					end
				else
					 local label_data_names = templateParams[labelDataPrefix..i]
					 if label_data_names then
					 	labelName = label_data_names
					 	label_data_names = mw.text.trim(label_data_names, '%[%]')
						local hasContent = templateArgs[label_data_names] and #templateArgs[label_data_names]>0
						-- + and use explicit wikidata replace the content with such if available from wikidata
						local isExplicitWikidataParam = templateParams[label_data_names..explicitWikidata]
						local isExplicitWikidataEnabled = false 
						if isExplicitWikidataParam then
							isExplicitWikidataEnabled = templateArgs[label_data_names]~=nil and mw.ustring.match(templateArgs[label_data_names], '^ *+$')
						end
						local skipContent = false
					 	if hasContent and not isExplicitWikidataEnabled then
					 		dataTemplate = templateArgs[label_data_names]
				 		else
							if isExplicitWikidataParam and not isExplicitWikidataEnabled then
								skipContent = true
							end
				 			dataTemplate = '{{{' ..label_data_names.. '}}}'
				 			
					 	end
					 	if not skipContent then
					 		table.insert(templateStructure, {label=labelName, data=dataTemplate, rowstyle=templateParams[rowStylePrefix..i], rowclass=templateParams[rowStyleClassPrefix..i], datastyle=templateParams[dataPrefix..i..styleSuffix], 
					 									 labelstyle=templateParams[labelPrefix..i..styleSuffix], indic=indic})
						end
				 	end
				end
			end
		end
	end
	table.sort(templateStructure, function (x, y) return x.indic<y.indic end)
	
	-- use wikidata / remove unused parameters
	if not isSelfUse then
		local entriesToRemove = {}
		local crossValidatedFields = {}
		
		for k,v in pairs(templateStructure) do
			if v.data then
				-- remove parameters that were explicitly defined to be removed
				local ignoreParam = mw.ustring.match(v.data, '^%-$')
				if ignoreParam then
					table.insert(entriesToRemove, 1, k)
				else
					-- otherwise if the template isn't full or if there is a Wikidata-beats tag - them try to use wikidata to fill it
					local m = mw.ustring.match(v.data, '{{{(.-)}}}')
					if v.label and templateParams[v.label..'-ויקינתונים-גובר'] then
						m = templateParams[v.label..'-ויקינתונים-גובר']
					end
					if m then
						m = mw.uri.decode( m ) -- some templates may add encoding and are preprocessed before
						local before = v.data
						local inWikidata, maintainceCats = fillMissingParamFromWikidata(m, templateParams, v, args.entityId, frame)
						if (v.data==nil or v.data=="") and v.label and templateParams[v.label..'-ויקינתונים-גובר'] then
							v.data = before
							inWikidata = true
						end
						
						if maintainceCats then
							table.insert(wikidataCats, maintainceCats)
						end
						
						if inWikidata then
							crossValidatedFields[m] = 1
							args.usingWikidata = true
						else
							-- if data isn't available remove it
							table.insert(entriesToRemove, 1, k)
							-- no need to cross validate it
							crossValidatedFields[m] = 1
						end
				
					end					
				end
			end
		end
		
		for k,v in pairs(templateArgs) do
			if crossValidatedFields[k]==nil and v and #v>0 and pageNs==0 and k~= 'בילד' and k~= 'תמונה' then
				local maintainceCats = crossValidateWikidata(k,templateParams, v, frame, args.entityId)
				if maintainceCats and #maintainceCats>0 then
					table.insert(wikidataCats, maintainceCats)
				end
			end
		end
		
		for k,v in pairs(entriesToRemove) do table.remove(templateStructure, v) end

		-- use wikidata in title
		if args.title then
			local m = mw.ustring.match(args.title, '{{{(.-)|(?)}}}') 
			if m then
				local inWikidata = false
				if templateParams[m..'-ויקינתונים'] then
					local wikidataParamValue = getPropertyByOptions(templateParams[m..'-ויקינתונים'], args.entityId) or nil
					if wikidataParamValue then
						args.title = wikidataParamValue
					end
				elseif templateParams[m..'-ויקינתונים-פשוט'] then
					-- use data should be taken from wikidata and link must not be added
					local wikidataParamValue = propertyLink.getLabel(templateParams[m..'-ויקינתונים-פשוט'])
					if wikidataParamValue then
						args.title = frame:preprocess(mw.ustring.gsub(args.title, '{{{('..m..')|?}}}', wikidataParamValue))
					end
				end
			end
		end
	end
	
	self.args = args
	self.templateStructure = templateStructure
	self.wikidataCats = wikidataCats
	self.isSelfUse = isSelfUse
	self.templateParams = templateParams
end

function infobox(frame)
	local infoObj = Infobox:new()
	infoObj:parseArgs(frame)
	return infoObj:render()
end

return 	{
	['מידע']=infobox,
	Infobox=Infobox
}