مۆدیوول:Wikidata2

بەڵگەدارکردنی مۆدیوول
-- local fallback = {'en', 'nb', 'da', 'nn', 'de', 'fr', 'es', 'it', 'pt'}local formatera = require('Module:Wikidata2/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 modulesendlocal weblink = require('Module:Weblink')local flags = require('Module:Wikidata2/Flags')local Infobox_Image = require('Module:InfoboxImage').Infobox_Imagelocal 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 غير موجودة."    },["noarabiclabel"] = "تصنيف:صفحات_ويكي_بيانات_بحاجة_لتسمية_عربية",["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 trueendreturn falseendfunction addTrackingCategory(prop,options)if No_Tracking_cat(options) then return prop endlocal cat =  require('Module:Wikidata/Track').makecategory1local category = cat(options)local nbsp = "&nbsp;"if options.nbsp and options.nbsp ~= "" then nbsp = "" endif prop and prop ~= '' thenif category and category ~= '' thenreturn prop .. nbsp .. categoryelse return prop .. nbsp endendendfunction catewikidatainfo(options)--[[  function to add tracking category ]]  --if (options.raw and options.raw ~= '') or (options.notracking and options.notracking== true) then return "" endif No_Tracking_cat(options) then return "" endlocal prop = options.propertylocal cat = ' [[' .. 'تصنيف:صفحات بها بيانات ويكي بيانات|'.. (prop or 'wikidata') .. ']]'if (not options.nolink or options.nolink == '')then return cat else return ''endendfunction countSiteLinks(id)numb = 0Table = {}local entity = mw.wikibase.getEntityObject(id)if entity and entity.sitelinks thenfor i, v in pairs(entity.sitelinks) do Table[v.site] = v.title numb = numb +1end--return Frame:extensionTag("source", mw.dumpObject( Table ),{ lang= 'lua'})endreturn numbendfunction make_format_num(String)local line = Stringline = mw.getCurrentFrame():preprocess("{{ {{{|safesubst:}}}formatnum: " .. String .. " }}")line = mw.ustring.gsub( line , '٫', '.' )line = mw.ustring.gsub( line , '٬', ',' )return line end--auktoritetsdatafunction formatcharacters(label, options)local formatcharacters = options.formatcharacters--if options.FormatfirstCharacter and options.num == 1 then --formatcharacters = options.FormatfirstCharacter --endif options.illwd2y and options.illwd2y ~= '' thenString2 = 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 Stringreturn caendif not formatcharacters or formatcharacters == '' thenreturn labelendif formatcharacters == 'lcfirst' thenreturn mw.getCurrentFrame():preprocess("{{lcfirst: " .. label .. " }}")elseif formatcharacters == 'ucfirst' thenreturn mw.language.getContentLanguage():ucfirst( label )elseif formatcharacters  == 'lc' thenreturn mw.getCurrentFrame():preprocess("{{lc: " .. label .. " }}")elseif formatcharacters == 'uc' thenreturn mw.getCurrentFrame():preprocess("{{uc: " .. label .. " }}")elseif formatcharacters == 'formatnum' thenreturn make_format_num( label )endreturn labelendfunction getqualifierbysortingproperty(claim, sortingproperty)for k, v in pairs(sortingproperty) doif claim.qualifiers and claim.qualifiers[v] and claim.qualifiers[v][1].snaktype == 'value' thenreturn claim.qualifiers[v][1].datavalue.value.time endendreturn nilendfunction getDate(claim, options)local sortingproperty = sortingpropertiesif type(options.sortingproperty) == 'table' thensortingproperty = options.sortingpropertyelseif type(options.sortingproperty) == 'string' thensortingproperty = {options.sortingproperty}endreturn getqualifierbysortingproperty(claim, sortingproperty) endfunction get_entityId(options)local id = options.entityId or options["entityId"]id = id or options.id or options["id"]if not id or id == "" thenif options.page and options.page ~= "" thenid = mw.wikibase.getEntityIdForTitle( options.page )endend--mw.log("id :" .. id)return id or ""endfunction getDateArb(claim, options)local sortingproperty = options.sortingproperty or 'P569'if claim.mainsnak.snaktype == 'value' thenlocal item = claim.mainsnak.datavalue.value['numeric-id']if claim.mainsnak.datavalue.value['entity-type'] == 'item' thenitem = 'Q' .. itemelseif claim.mainsnak.datavalue.value['entity-type'] == 'property' then item = 'P' .. itemendreturn formatStatements({property = sortingproperty, entityId = item, firstvalue = 'true', sortbytime = 'chronological', noref = 'true'})endendfunction descriptionIn(langcode , id) -- returns item description for a given languagelocal lan = langcode or 'ar'local entity = getEntityFromId(id)--[[local description, lange = mw.wikibase.getDescriptionWithLang( id )--mw.log( "descriptionIn:description : " .. description ",lange : " .. lange ".")if lange == lanthen--return descriptionreturn mw.getCurrentFrame():extensionTag("source", mw.dumpObject( description ),{ lang= 'lua'})else--mw.log( "descriptionIn:langcode : " .. langcode ",lange : " .. lange ".")--return nilreturn mw.getCurrentFrame():extensionTag("source", mw.dumpObject( description ),{ lang= 'lua'})--return strend]]if entity and entity.descriptions 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 thenreturn description.valueelse return nil endendendendfunction labelIn(langcode,id) -- returns item label for a given languageif not mw.wikibase then return nil endlocal lang = langcodeif not langcode or langcode  == "" then lang  = "ar" endif type(id) ~= "string" then id = tostring(id) endlocal label = mw.wikibase.getLabelByLang( id , lang ) or nilreturn label--[[ 2nd old waylocal label, lange = mw.wikibase.getLabelWithLang( id )if lange == langthenreturn labelelsereturn nil--return strend ]]--[[ old waylocal entity = mw.wikibase.getEntityObject(id)if entityand entity.labels and entity.labels[''..lang..'']and entity.labels[''..lang..''].value thenlocal lang = entity.labels[''..lang..'']if lang['language'] == lang thenreturn entity.labels[''..lang..''].valueelse return nil endend]]endfunction 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.typeand 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 IDendendfunction comparedates(a, b)  -- returns true if a is earlier than B or if a has a date but not bif a and b thenreturn a > belseif a thenreturn trueendendfunction getonly(claims, options) -- options.getonly -- options.getonlyproperty local claims2 = {}--mw.log("wikidata2 : getonly:" .. options.getonly )for i, j in pairs(claims) dolocal 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.idif id thenlocal traff = falselocal t2 = formatStatements( {property = (options.getonlyproperty or "P31"), entityId = id, noref = 'true', raw = 'true' })if t2 and #t2 > 0 thenfor k, state in pairs( t2 ) dofor j2, only in pairs(mw.text.split(options.getonly,',')) doif state.item == only thentraff = trueendendendendif traff thentable.insert(claims2, j)endendendreturn claims2endfunction claimindex(claims, options)local claims2 = {}for j, index in pairs(mw.text.split(options.claimindex,',')) doif tonumber(index) and #claims >= tonumber(index) thentable.insert(claims2, claims[tonumber(index)])endendreturn claims2endfunction avoidvalue(claims, options)-- options.avoidvalue -- to avoid valueslocal claims4 = {}local add2claimslocal avoidvalueif(type(options.avoidvalue) == 'string') then avoidvalue = mw.text.split(options.avoidvalue,',')elseif(type(options.avoidvalue) == 'table') then avoidvalue = options.avoidvalueelse return claimsend--mw.log("avoidvalue: " .. mw.dumpobject(options.avoidvalue))for i, j in pairs( claims ) do--mw.log('t:' .. t)ID = get_snak_id(j)add2claims = trueif ID then    for k, t in pairs(avoidvalue) do--mw.log("ID: " .. ID)if ID == t thenadd2claims = falseendendif add2claims thentable.insert( claims4, j)endendendreturn claims4endfunction prefervalue(claims, options)local claims3 = {}--mw.log("prefervalue: " .. mw.dumpobject(options.prefervalue))local prefervalueif(type(options.prefervalue) == 'string') then prefervalue = mw.text.split(options.prefervalue,',')elseif(type(options.prefervalue) == 'table') then prefervalue = options.prefervalueelse return claimsendfor k, t in pairs(prefervalue) do--mw.log('t:' .. t)for i, j in pairs( claims ) dolocal active = falseID = get_snak_id(j)if ID then--mw.log("ID: " .. ID)if ID == t and not active thentable.insert( claims3, j)active = true--mw.log("ID == t" .. t)endendendendreturn claims3endfunction preferqualifier(claims, options)-- options.preferqualifier-- options.preferqualifiervaluemw.log("preferqualifier: " .. options.preferqualifier)local claims2 = {}for i, statement in pairs( claims ) do -- if statement.qualifiers and statement.qualifiers[options.preferqualifier:upper()] thenif options.preferqualifiervalue and options.preferqualifiervalue ~= '' thenlocal active = falsefor 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 = kasofor ii, quall in pairs( statement.qualifiers[options.preferqualifier:upper()] ) do--mw.log( "value " .. value )snaktype = quall.snaktypeif snaktype == "value" thenty = quall.datavalue.value['id'] if ty and ty == t  and not active then--if value == t and not active thentable.insert( claims2, statement)active = true--endendendendendelsetable.insert( claims2, statement)endendendreturn claims2endfunction avoidqualifier(claims, options)-- options.avoidqualifier-- options.avoidqualifiervalueif not options.avoidqualifier or options.avoidqualifier == "" then return claims endlocal av = options.avoidqualifier:upper()local claims2 = {}for i, statement in pairs( claims ) doif not statement.qualifiers or not statement.qualifiers[options.avoidqualifier:upper()] thentable.insert( claims2, statement)elseif statement.qualifiers and statement.qualifiers[av] thenif options.avoidqualifiervalue and options.avoidqualifiervalue ~= '' thenlist = {}if(type(options.avoidqualifiervalue) == 'string') then list = mw.text.split(options.avoidqualifiervalue,',')elseif(type(options.avoidqualifiervalue) == 'table') then list = options.avoidqualifiervalueendlocal active = truefor k, t in pairs( list ) dofor ii, quall in pairs( statement.qualifiers[av] ) doif quall.snaktype == "value" and quall.datavalue and quall.datavalue.value and quall.datavalue.value['id'] thenif quall.datavalue.value['id'] == t thenactive = falseendendendendif active then table.insert( claims2, statement)endendendendreturn claims2endfunction sortbyqualifier(claims, options)table.sort(claims, function(a,b)local timeA = getDate(a, options)local timeB = getDate(b, options)if options.sortbytime == 'inverted' thenreturn comparedates(timeB, timeA)elsereturn comparedates(timeA, timeB)endend)return claimsendfunction sortbyqualifiernumber(claims, options)local sortingproperty = options.sortingpropertyif type(options.sortingproperty) == 'string' thensortingproperty = {options.sortingproperty}endtable.sort(claims, function(a,b)local timeA = getqualifierbysortingproperty(a, sortingproperty)local timeB = getqualifierbysortingproperty(b, sortingproperty)if options.sortbynumber == 'inverted' thenreturn comparedates(timeB, timeA)elsereturn comparedates(timeA, timeB)endend)return claimsendfunction 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' thenreturn comparedates(timeB, timeA)elsereturn comparedates(timeA, timeB)endend)return claimsendfunction getEntityFromId( id )if id and id ~= "" then--if not(mw.wikibase.isValidEntityId(id)) or not(mw.wikibase.entityExists(id)) then--return false--endreturn mw.wikibase.getEntityObject( id )elsereturn mw.wikibase.getEntityObject() endendfunction 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' )    endend function formatError( key )    return i18n.errors[key]endfunction Labelfunction( entityId, label ,labeloption , options) -- label with no arwiki sitelinkif options.illwd2nowd  and options.illwd2nowd  ~= '' then noWD='' else noWD='y' endlocal jlabel = label --formatcharacters(label, options) -- The labellocal ar = labelIn('ar',entityId ) -- The arabic labellocal arlabel = ar --formatcharacters(ar, options) if labeloption and labeloption ~= '' thenjlabel = labeloption elseif options.illwd2  and options.illwd2  ~= '' thenif arlabel and arlabel ~= '' thenjlabel = mw.getCurrentFrame():expandTemplate{ title = 'Ill-WD2', args = {arlabel, fromlua="t", id=entityId, y = (options.illwd2y or '') } }--jlabel = arlabelelse jlabel  = mw.getCurrentFrame():expandTemplate{ title = 'Ill-WD2', args = {id=entityId, fromlua="t", target='en', y = (options.illwd2y or '') } }--jlabel  = labelendelseif options.enlabelcate and options.enlabelcate  ~= '' thenif not arlabel or arlabel == '' thenjlabel = label --formatcharacters(label, options) if jlabel and jlabel ~= '' then jlabel = jlabel ..' [['.. i18n.noarabiclabel ..'|'.. entityId ..']]'end endelse--if options.justarabic and options.justarabic  ~= '' thenif arlabel and arlabel ~= ''then jlabel = arlabelelse jlabel = nilendendif jlabel and jlabel ~= ''thenreturn jlabel.. catewikidatainfo(options)endendfunction formatOneStatement( statement ,ref ,  options)local vava = nillocal stat = formatStatement( statement, options )if stat thenif not stat.qualifiers then stat.qualifiers = {}endlocal s = stat.valuelocal P585 = stat.qualifiers.P585 or ""local tf = stat.tifrlocal awardqual = stat.fotolocal pr = stat.pr--local utgivort = stat.utgivortlocal ro = stat.rolocal qp1a = stat.qp1alocal onlyqualifier = stat.onlyqualifierlocal qp1 = stat.qp1local qp2 = stat.qp2local qp3 = stat.qp3local qp4 = stat.qp4local qp5 = stat.qp5local reff  =stat.refflocal QPrefix local QSuffixif s == '' then s = nil endif s thenif reff and options.reff and options.reff ~= ''  thens= s .. reffendif options.template and options.template ~= '' thens = 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} }endif options.football and options.football ~= '' thens =mw.getCurrentFrame():expandTemplate{ title = "صندوق معلومات سيرة كرة قدم/سطر فريق", args = {stat.qualifiers.P580 or "",stat.qualifiers.P582 or "",s,stat.amatch,stat.goal} }endif options.office and options.office ~= '' thens = 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} } endfunction qoo(Prefix,qualpref,p,Suffix)if p and p ~='' then return mw.text.tag('small', {}, (Prefix or ' (').. (qualpref or '') .. p .. (Suffix or ')'))  endendQPrefix = options.qualifierprefixQSuffix = options.qualifiersuffixif qp1 and qp1 ~='' and options.qual1 and options.qual1 and qp1a and qp1a ~='' and options.qual1a and options.qual1a ~= ''thens = s .. qoo(QPrefix, options.qual1pref, qp1, QSuffix) .. qoo(QPrefix, options.qp1apref, qp1a, QSuffix)elseif qp1 and qp1 ~='' and options.qual1 and options.qual1 ~= '' thens = s .. qoo(QPrefix, options.qual1pref, qp1, QSuffix)elseif qp1a and qp1a ~='' and options.qual1a and options.qual1a ~= '' thens = s .. qoo(QPrefix, options.qp1apref, qp1a, QSuffix)endif qp2 and qp2 ~='' and options.qual2 and options.qual2 ~= '' then s = s .. qoo(QPrefix, options.qual2pref, qp2, QSuffix) endif qp3 and qp3 ~='' and options.qual3 and options.qual3 ~= '' then s = s .. qoo(QPrefix, options.qual3pref, qp3, QSuffix) endif qp4 and qp4 ~='' and options.qual4 and options.qual4 ~= '' then s = s .. qoo(QPrefix, options.qual4pref, qp4, QSuffix) endif qp5 and qp5 ~='' and options.qual5 and options.qual5 ~= '' then s = s .. qoo(QPrefix, options.qual5pref, qp5, QSuffix) endif options.justthisqual and options.justthisqual ~= '' then if onlyqualifier then s = onlyqualifier else s = nil   -- We need only the qualifier end endif ro and ro ~='' and options.withro and options.withro ~= '' then s = s .. qoo(QPrefix, '' , ro, QSuffix) endif options.withdate and options.withdate ~= '' thenif P585 and P585 ~=''  thenif 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)endendendif awardqual and options.awardqua and options.awardqua ~= '' then s = s .. qoo(QPrefix, '' , awardqual, QSuffix) endlocal bothdates = options.withintervall or options.bothdatesif tf and bothdates and bothdates  ~= '' thenif bothdates == 'line' then s = s .. mw.text.tag('br') .. qoo(QPrefix, '' , tf, QSuffix)elseif bothdates == 'before' then s = qoo(QPrefix, '' , tf, QSuffix) .. selse s = s .. qoo(QPrefix, '' , tf, QSuffix)endend--if utgivort and options.withutgivort and options.withutgivort ~= '' then--if options.withutgivort == 'قوسين' then s = s .. ' ' .. qoo(QPrefix, '' , utgivort, QSuffix)--else s = s .. ' ' .. utgivort--end--endif pr and pr ~= '' and options.getsimpleproperty and options.getsimpleproperty ~= '' thenif 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 .. '')endendif type(ref) == 'table' or (options.noref and options.noref ~='') or (options.justthisqual and options.justthisqual ~='') then--table.insert( formattedStatements, s )vava =  s elselocal t = formatReferences( statement, options )stat.ref = tif options.justref and options.justref ~= '' thenvava =  telseif options.onlyvaluewithref and options.onlyvaluewithref ~= '' thenif t and t ~= "" thenvava =  s .. t endelse vava =  s .. t endendend--table.insert(statementsraw, stat)endreturn { v = vava , raw = stat}endfunction filter_claims( claims , options)local claims = claims--======================================================if options.avoidqualifier and options.avoidqualifier ~= '' then -- to avoid value with a given qualifierclaims = avoidqualifier(claims, options)end--======================================================if options.preferqualifier and options.preferqualifier ~= '' thenclaims = preferqualifier(claims, options)end--======================================================-- options.avoidvalueif options.avoidvalue and options.avoidvalue ~= '' thenclaims = avoidvalue(claims, options)end--======================================================-- options.prefervalueif options.prefervalue and options.prefervalue ~= '' thenclaims = prefervalue(claims, options)end--======================================================-- options.getonlyif options.getonly and options.getonly ~= '' thenclaims = getonly(claims, options)end--======================================================if not options.langpref or options.langpref == '' thenlocal claims7 = {}for i, statement in pairs( claims ) doif statement.qualifiers and statement.qualifiers.P407 thenfor k, v in pairs( statement.qualifiers.P407 ) doif v.snaktype == 'value' and v.datavalue.value['numeric-id'] == 13955 then -- Q13955 = 'العربية'table.insert( claims7, statement )endendelseif statement.qualifiers and statement.qualifiers.P282 thenfor k, v in pairs( statement.qualifiers.P282 ) doif v.snaktype == 'value' and v.datavalue.value['numeric-id'] == 8196 then -- Q8196 = 'أبجدية عربية'table.insert( claims7, statement )endendendendif #claims7 > 0 thenclaims = claims7endend--======================================================if options.sortbytime == 'chronological' or options.sortbytime == 'inverted' thenclaims = sortbyqualifier(claims, options)elseif options.sortbynumber == 'chronological' or options.sortbynumber == 'inverted' thenclaims = sortbyqualifiernumber(claims, options)elseif options.sortbyarbitrary == 'chronological' or options.sortbyarbitrary == 'inverted' thenclaims = sortbyarb(claims, options)end--======================================================local firstvalue =  options.enbarten or  options.firstvalueif firstvalue and firstvalue ~='' and #claims > 1 thenif firstvalue == '2' thenclaims = {claims[2]}elseif firstvalue == '3' and #claims > 2 thenclaims = {claims[3]}elseif firstvalue == '4' and #claims > 3 thenclaims = {claims[4]}elseif firstvalue == '5' and #claims > 4 thenclaims = {claims[5]}elseif firstvalue == '6' and #claims > 5 thenclaims = {claims[6]}elseif firstvalue == '7' and #claims > 6 thenclaims = {claims[7]}elseif firstvalue == '8' and #claims > 7 thenclaims = {claims[8]}elseif firstvalue == '9' and #claims > 8 thenclaims = {claims[9]}elseclaims = {claims[1]}endendlocal numval =  options.numvalif numval and type(numval) ~= "number" then numval = tonumber(numval)endif numval and type(numval) == "number" and #claims > 1 and #claims > numval thenlocal claimsnumval= {}local ic = 1while (numval >= ic) and (#claims >= ic) dotable.insert( claimsnumval, claims[ic] ) ic =ic +1endclaims = claimsnumval;endreturn claimsendfunction 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 tabellclaims = 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 = mw.wikibase.resolvePropertyId( options.property:upper() )    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 cleanlyif options.rank == 'best' or not options.rank then --claims = entity:getAllStatements( property )claims = entity:getBestStatements( property )elseif options.rank == 'valid' thenfor i, statement in pairs( entity.claims[ property ] ) do    if statement.rank == 'preferred' or statement.rank == 'normal' then    table.insert( claims, statement )    endendelseif options.rank == 'all' thenfor i, statement in pairs( entity.claims[property] ) dotable.insert( claims, statement )endelsefor i, statement in pairs( entity.claims[property] ) doif statement.rank == options.rank thentable.insert( claims, statement )endendendendclaims = filter_claims( claims , options)local statementsraw = {}local All_claims = claimsif claims then--==========================================if options['property-module'] or options['property-function'] thenif not options['property-module'] or not options['property-function'] thenreturn formatError( 'unknown-property-module' )endlocal formatter = require ('Module:' .. options['property-module'])if not formatter thenreturn formatError( 'property-module-not-found' )endlocal fun = formatter[options['property-function']]if not fun thenreturn formatError( 'property-function-not-found' )endmw.log("work with property-module: " .. options['property-module'] .. "|" .. options['property-function'])return fun( claims, options )else --==========================================for i, statement in pairs( claims ) dooptions.num = ilocal va = formatOneStatement( statement,ref, options )if va.v thentable.insert( valuetable, va.v )endtable.insert( statementsraw, va.raw )endendendlocal priff = ""local Separator = options.separator-- or ""local Conjunction = options.conjunction-- or ""--if Conjunction and Conjunction == "br" then Conjunction =  "\n" endif (Separator and Separator == "br") or (Conjunction and Conjunction == "br")  then Separator = mw.text.tag('br')Conjunction = mw.text.tag('br')endif Separator and Separator == "*"  then priff = "\n*" Separator = "\n*" Conjunction = "\n*" endif Separator and Separator == "#"  then priff = "\n#" Separator = "\n#" Conjunction = "\n#" endlocal tot = mw.text.listToText( valuetable, Separator, Conjunction )if #valuetable > 1 thentot = priff .. totendif tot == '' then tot = nil endif options.raw and options.raw ~= '' thenif options.rawtolua and options.rawtolua ~= '' thenreturn  mw.getCurrentFrame():extensionTag("source", mw.dumpObject(statementsraw),{ lang= 'lua'})endreturn statementsrawendif options.returnnumberofvalues and (options.returnnumberofvalues ~= "" or options.returnnumberofvalues == true ) thenreturn tot, #valuetableendif options.numberofclaims and options.numberofclaims ~= '' thenreturn #All_claimsendreturn totendfunction p.formatAndCat(args)if args then Frame_args = args endif not args then return nil endargs.linkback = args.linkback or trueargs.addcat = trueif args.value thenif args.value == '-' then return nil endlocal val = args.value .. p.addTrackingCat(args.property)val = p.addLinkBack(val, args.entity, args.property)return valend return p.formatStatementsFromLua( args )endfunction formatReferences( statement, options )local iclocal slocal statementreferences = statement.referenceslocal reference = {}local numberofref = tonumber(options.numberofreferences) or 7if statementreferences thenlocal cite = require(  citetitle  )ic = 1for i, ref in pairs( statementreferences ) doif ref.snaks thenif numberofref >= ic thens =  cite.citeitem2(ref , options )if s and s ~= "" then ic = ic + 1table.insert(reference, s)endendendendendlocal final = table.concat(reference)if final and final ~= '' thenfinal = final .. i18n.caterefendreturn finalendfunction formatqualifiers( statement,s, options )s.qualifiers = {}function qua(p,firstvalue,modifytime)if p and p ~='' thenvvv = formatStatements({property =p,enlabelcate = 't', firstvalue = (firstvalue or ''),modifytime = (modifytime or 'longdate'), noref = 'true'}, statement.qualifiers) or ''s.qualifiers[p] = vvvreturn vvvendendif options.template and options.template ~= '' thens.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)endif options.football and options.football ~= '' thenif statement.qualifiers.P1350 or statement.qualifiers.P1351 thens.amatch = qua("P1350",'true')s.goal = qua("P1351",'true')endendif (options.football and options.football ~= '' ) or (options.office and options.office ~= '') thens.start1 = qua("P580",'true')s.finish1 = qua("P582",'true')endif options.office and options.office ~= '' thenif statement.qualifiers.P580 or statement.qualifiers.P582 or statement.qualifiers.P1365 or statement.qualifiers.P1366 thens.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")endendif options.withdate and options.withdate ~= '' then--if statement.qualifiers.P585 thens.P585 = qua("P585",'true',options.modifyqualifiertime)end    local qwe = options.qwerif statement.qualifiers.qwe  thens.ro = qua(qwe,'true')end--if statement.qualifiers.P574 then--s.dateoftaxpub = qua("P574",'true',options.modifyqualifiertime)--end--[[if statement.qualifiers.P405 thenlocal author = {}for i, j in pairs(statement.qualifiers.P405) doif j.snaktype == 'value' thenlocal item = 'Q' .. j.datavalue.value['numeric-id']local authorname = formatStatements({property = "P428", entityId = item, noref = 'true', firstvalue = 'true'})if author and authorname ~= '' thentable.insert(author, formatEntityId(item, {label = authorname }).value)elsetable.insert(author, formatEntityId(item, {}).value)endendends.auktor = mw.text.listToText(author, ', ', ' & ')end--]]local bothdates_option = options.withintervall or options.bothdatesif  bothdates_option and bothdates_option  ~= '' thenif statement.qualifiers.P580 or statement.qualifiers.P582 thenlocal f = qua("P580",'true',options.modifyqualifiertime)local t =  qua("P582",'true',options.modifyqualifiertime)s.tifr = f .. '–' .. tendendif options.awardqua and options.awardqua ~= '' then if statement.qualifiers.P585 or statement.qualifiers.P1346 thenlocal fo = qua("P585",'true',options.modifyqualifiertime)local to = qua('P1346','true')s.foto = fo .. ' ' .. mw.text.tag('span', {}, ' ' .. to  .. '')endendfunction quaaal(opti,options)if opti and opti ~=''  and statement.qualifiers[opti] thenkkk = 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 ] = kkkreturn kkkendend--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 'ar')}, statement.qualifiers)--endif options.justthisqual and options.justthisqual ~= '' and statement.qualifiers[options.justthisqual] thens.onlyqualifier = quaaal(options.justthisqual,options)endif options.qual1 and options.qual1 ~= '' and statement.qualifiers[options.qual1] thens.qp1 = quaaal(options.qual1,options) endif options.qual1a and options.qual1a ~= '' and statement.qualifiers[options.qual1a] thens.qp1a = quaaal(options.qual1a,options) endif options.qual2 and options.qual2 ~= '' and statement.qualifiers[options.qual2] then s.qp2 = quaaal(options.qual2,options) endif options.qual3 and options.qual3 ~= '' and statement.qualifiers[options.qual3] thens.qp3 = quaaal(options.qual3,options) endif options.qual4 and options.qual4 ~= '' and statement.qualifiers[options.qual4] thens.qp4 =  quaaal(options.qual4,options) endif options.qual5 and options.qual5 ~= '' and statement.qualifiers[options.qual5] thens.qp5 = quaaal(options.qual5,options) endendfunction formatStatement( statement, options )    if options['claim-module'] or options['claim-function'] thenif 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 ~= ''  thens.qualifiers = {}if statement.qualifiers thenqualu = formatqualifiers( statement,s, options )--if qualu and qualu ~= '' then table.insert(qualu) endendif statement.references thenif options.reff and options.reff ~= ''  thens.reff  = formatReferences( statement, options )end endendreturn selseif not statement.type thenreturn formatSnak( statement, options )    endreturn {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' )}    endendlocal skiip = {["P106"] = {"Q42857"  ,  -- prophet"Q14886050"  , -- terrorist"Q2159907"  , -- criminal}}--[[function to get countries flags without reload large countries items]]function get_property1(options , item)local flagprop = { "p27","p1532","p17","p495","p1376" }local work_flag = falselocal property1 = options.property1 or options["property1"]if string.lower(property1) == "p41" thenfor k, l in pairs(flagprop) doif string.lower(options.property) == l then work_flag = trueendendendcaca = ''local size = options.size or ""if size == "" then size = "20" endif work_flag thenlocal flag = flags[item]if flag and flag ~= '' then -- return real imageif options.image and options.image ~= '' then -- return real imagecaca = '[[file:' .. flag  .. '|'.. size ..'px|'..'border'..']]' mw.log("get flag for item ".. item )endendendif caca == "" thencaca = 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' })endreturn cacaendfunction formatwikibaseitem( datavalue, datatype, options ) --[[  datatype  wikibase-item   ]]local item = getEntityIdFromValue( datavalue.value )local itemValue = formatEntityId( item , options ).valuelocal Format = options.formatting or options["formatting"]local Skipped = skiip[options.property] or {}for k, v in pairs(Skipped) doif datavalue.value.id == v then return {value = ""}    endendif Format and Format  ~= '' thenif 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'}endelseif 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 listreturn {value = formatsitelink(datavalue.value.id , options ) }elsereturn {value = formatFromPattern( formatcharacters(datavalue.value, options), options )}endelseif options.property1 and options.property1 ~= '' and options.property1:upper():sub(1,1) =="P" thenfor i, statement in pairs( datavalue ) docaca = get_property1(options , item)if itemValue and itemValue  ~= '' thenif caca and caca  ~= '' then cooooca = (options.property1pref or '') ..''.. caca ..''.. (options.property1suff or '')if options.property1after and options.property1after ~= "" thenreturn {value = itemValue .. cooooca } elsereturn {value = cooooca .. ' '.. itemValue } endelsereturn {value = itemValue  }endendend elseif options.propertyimage and options.propertyimage ~= '' thenlocal p_f = options.propertyimageformatting or options.formattingpropertyimagefor i, statement in pairs( datavalue ) dolocal 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 } elseendend elseif options.property2 and options.property2 ~= '' thenfor i, statement in pairs( datavalue ) dolocal 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  ~= '' thenif caca and caca  ~= '' thenreturn {value =  caca .. ' '.. itemValue  } else return {value = itemValue  } endendend    elsereturn {value = formatEntityId( item, options ).value, item = item }    endendfunction formatwikibaseproperty( datavalue, datatype, options ) --[[  datatype  wikibase-property   ]] if options.formatting and options.formatting  ~= '' thenif options.formatting == 'raw' then tid = getEntityIdFromValue( datavalue.value )elseendelse tid =  formatEntityId( getEntityIdFromValue( datavalue.value ), options ).valueendreturn {value = tid}endfunction formattabulardata( datavalue, datatype, options ) --[[  tabular-data ]]data=  '[[commons:' .. datavalue.value .. '|' .. datavalue.value .. ']]'return {value = data}endfunction formatgeoshape( datavalue, datatype, options ) --[[  geo-shape  ]]shape =  '[[commons:' .. datavalue.value .. '|' .. datavalue.value .. ']]'return {value = shape}endfunction formatcommonsMedia( datavalue, datatype, options ) --[[ commonsMedia ]]local size = options.size or ""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 = size endtid = Infobox_Image( params )--tid = '[[file:' .. datavalue.value  .. '|'.. (options.size or '20')..'px|border]]' --if options.center and options.center ~= "" then--tid = '[[file:' .. datavalue.value  .. '|'.. (options.size or '20')..'px|border|center]]' --endelsetid =  formatcharacters(datavalue.value, options)endreturn {value = tid}endfunction 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..'' ) }endfunction formatstring( datavalue, datatype, options ) --[[  datatype  string  -  external-id  ]]--old value: auktoritetsdata , auktoritetsdata2 , auktoritetsdata3local par = options.patternif options.stringpattern and options.stringpattern ~= "" then--mw.log(options.stringpattern)tid = mw.ustring.gsub( options.stringpattern, '$1', datavalue.value ) elseif par and par ~= '' thenif 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 )endelse tid =  formatcharacters(datavalue.value, options)endreturn {value = tid}endfunction formatexternalid( datavalue, datatype, options )if options.pattern and options.pattern ~= '' thenpar = options.patternlocal 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.wikibasethen  plabel =  mw.wikibase.label( options.property ) or pp         end        ppp = mw.ustring.gsub( pp, ' ', '_' )if patter and patter ~= '' then   -- if P1630 are thereif par == "autourl" then -- like http://example.com/$1.html tid =  pppelseif 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 .. ']' elsetid =  formatFromPattern( formatcharacters(datavalue.value, options), options )endelse   --  P1630 are not thereif par ==  "autourl" or par ==  "autourl2" or par == "autourl3" or par == "autourl4"thentid =  formatcharacters(datavalue.value, options)  --just return valueelsetid =  formatFromPattern( formatcharacters(datavalue.value, options), options )endendelse tid =  formatcharacters(datavalue.value, options) --just return valueendreturn {value = tid}endfunction 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 ~= '' thenif options.modifytime == 'q' thenlocal mall = datavalue.value.timetid = mw.getCurrentFrame():preprocess(mall)elseif options.modifytime == 'precision' thenlocal mall = datavalue.value.precisiontid = mw.getCurrentFrame():preprocess(mall)endendreturn {value = tid}endfunction 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  ~= '' thenif 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 = }elseendelsepro =mw.getCurrentFrame():preprocess('{{ {{{|safesubst:}}}#invoke:Coordinates|coord'.. '|'.. coord.latitude.. '|'.. coord.longitude.. '|display=inline'.. '|globe:'.. globe2 ..'_type:landmark'.. '|format='..(options.formatcoord or '')..'}}')..catewikidatainfo(options) endreturn {value = pro }endfunction formatquantity( datavalue, datatype, options )--[[  datatype quantity  ]] local amount, unit, cat = datavalue.value.amount, datavalue.value.unit, nilamount = mw.ustring.gsub( amount , '+', '' )if unit thenunit = unit:match('Q%d+')endlocal number = formatera.newFromWikidataValue(datavalue.value)local unitraw = unitif unit then-- يتحقق اذا كان هناك اي اختصار لوحدة القياس--if lab and ( not options.nounitshort or options.nounitshort == '' )  thenif options.unitshort and options.unitshort ~= '' thenlocal 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.valuecat = s.catelse -- om det inte finns en f?rkortninglocal s = formatEntityId( unit, {nolink = options.nounitlink ,enlabelcate ='t'})unit = s.valuecat = s.catendendif options.formatcharacters and options.formatcharacters =="formatnum" thenamount = make_format_num( amount )endlocal Value = amount .. ' ' .. (unit or '')if options.nounit and options.nounit ~= "" thenValue = amountendreturn {value = Value, amount = amount, unit = unit, unitraw = unitraw, cat = cat}endfunction formaturl( datavalue, datatype, options )--[[  datatype  url  ]] local label = options.labelif options.urllabel and options.urllabel  ~= '' thenlabel = options.urllabel     endva =  mw.ustring.gsub( datavalue.value, ' ', '_' )if not label and  options.property =='P856' then label = 'الموقع الرسمي' endif options.displayformat and options.displayformat == "weblink" thenreturn {value = weblink.makelink(va ) }endif options.formatting and options.formatting == "raw" thenreturn {value = va }endif label and label ~= '' thenpro = '[' .. va .. ' ' .. label .. ']' else--if property =='P856' then pro =  formatFromPattern( formatcharacters(va, options), {pattern = '[$1 الموقع الرسمي]'} )--elsepro = va--endendreturn {value = pro }endfunction formatmonolingualtext( datavalue, datatype, options ) -- showlanglocal text = datavalue.value.textif options.textformat and options.textformat == "text" thenreturn {value = text}endlocal Moduletext = require 'Module:wikidata2/monolingualtext'local tid = Moduletext._main( datavalue, datatype, options )return {value = tid}endfunction 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' )}    endendfunction formatEntityId( entityId, options )local label = options.label or mw.wikibase.label( entityId )if label == '' thenlabel = mw.wikibase.label( entityId ) or nilend    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}    endendfunction sitelink_g( id , wikisite ) --[[        function to get any link from any sister project ]]if not mw.wikibase then return '' endlocal site = wikisite or 'arwiki'local link = mw.wikibase.sitelink( id , site ) or ""--mw.log("mw.wikibase.sitelink,site: " .. site.. ",link:" .. link )return linkendfunction sitelink( id , wikisite )if not mw.wikibase then return '' endlocal site = wikisite or 'arwiki'--local link = mw.wikibase.getSitelink( id , site ) or ""--return linklocal entity = mw.wikibase.getEntityObject(id)if entityand entity.sitelinks and entity.sitelinks[''..site..'']and entity.sitelinks[''..site..''].site and entity.sitelinks[''..site..''].title thenif entity.sitelinks[''..site..''].site == site thenreturn entity.sitelinks[''..site..''].titleelse return ''endendendfunction formatsitelink( entityId, options ) --[[ function to get only the value with link ]]     local link = sitelink( entityId )    if link and link ~= ''  thenif 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 ''    endendfunction 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--endendfunction p.getEntity( id ) if type(id) == 'table' then return id endreturn getEntityFromId(id)endfunction p.translate(str, rep1, rep2)str = i18n[str] or strif rep1 and (type (rep1) == 'string') thenstr = str:gsub('$1', rep1)endif rep2 and (type (rep2) == 'string')thenstr = str:gsub('$2', rep2)endreturn strendfunction p.getId(snak)if (snak.snaktype == 'value') thenif snak.datavalue.type == "wikibase-entityid" then return 'Q' .. snak.datavalue.value['numeric-id']endendendfunction p.addLinkBack(str, id, property)if not id then id = p.getEntity() endif not id then return str endif type(property) == 'table' then property = property[1] endif type(id) == 'table' then id = id.id endlocal class = ''if property thenclass = 'wd_' .. string.lower(property)endlocal 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=ar')url.fragment = propertyurl = 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 endlocal entity = mw.wikibase.getEntity(pItem)if not entity then return false endlocal claims31local claims279if entity.claims then if property and property ~= '' thenclaims31 = entity.claims[property] elseclaims31 = entity.claims['P31'] claims279 = entity.claims['P279'] endelsereturn falseendif not claims31 and not claims279 then return false endlocal parentIds = {}if claims31 and #claims31 > 0 thenfor i, v in ipairs(claims31) do parentIds[#parentIds+1] = p.getId(v.mainsnak) endendif claims279 and #claims279 > 0 thenfor i, v in ipairs(claims279) do parentIds[#parentIds+1] = p.getId(v.mainsnak) endend-- check if searched parent or exit item is reached or do recursive callif not parentIds[1] or #parentIds == 0 then return false endlocal itemString = ""local result = nilfor i, qid in ipairs(parentIds) doif not qid then return false end--itemString = "Q" .. vitemString = qidif itemString == pParent then -- successful!return trueelseif itemString == pExitItem then --or itemString == "Q35120"  -- exit if either "exit item" or node item (Q35120) is reachedreturn falseelseif pDepth+1 < pMaxDepth thenresult = isParent(property, itemString, pParent, pExitItem, pMaxDepth, pDepth+1)else return false endif result == true then return result endendenddo return false endendfunction p.Subclass(options)if options then Frame_args = options endlocal parent = options.parent or ""local id = options.id or ""local Entity = getEntityFromId(id) if Entity then id = Entity.id endlocal property = options.property or "P31"if parent == "" or id == "" or property == "" then return false endlocal tab = mw.text.split(options.parent,',')local result = mw.wikibase.getReferencedEntityId( id , property,  tab  ) -- { 'Q5', 'Q2095' } )if not result and property == "P31" thenresult = mw.wikibase.getReferencedEntityId( id , "P279" ,  tab  )endif result then return true endendfunction old_isSubclass(options)if not options.parent then return false endlocal maxDepthmaxDepth = tonumber(options.maxDepth) or 10if not type(maxDepth) == "number" then maxDepth = 5 endproperty = options.propertylocal resultresult = isParent(property, options.id, options.parent , options.exitItem, maxDepth)if options.returnInt thenif result == true then return 1 else return nil endelsereturn resultendendfunction p.formatSnak( snak, options )    return formatSnak( snak, options )endfunction p.getLabel( entity, lang )     return labelIn( lang , entity )endfunction p.formatEntityId( entityId, options )return formatEntityId( entityId, (options or {}) )end function p.formatStatements( frame, key )if frame.args thenif type(key)  == 'table' and key ~= {}  then else Frame_args = frame.args endend --[[        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 )    endif 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    endif args.addTrackingCat and args.addTrackingCat ~= '' then   -- add tracking catprop =  addTrackingCategory(prop,frame.args)endif args.mainsuffixAfterIcon and args.mainsuffixAfterIcon ~= '' then   -- another suffix but after wikidata iconprop =  prop .. args.mainsuffixAfterIcon endelse     if args.NoPropValue and args.NoPropValue ~= '' then -- value if no local value and no wikidata value      prop = args.NoPropValue    endend    if args.returnnumberofvalues and args.returnnumberofvalues ~= "" thenmw.log( "valuesnumb: " .. valuesnumb )         return s , valuesnumb    end    return propendfunction p.formatStatementsFromLua( options, key ) --  main function but to use from lua moduleif 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    endif 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    endif options.addTrackingCat and options.addTrackingCat ~= '' then   -- add tracking cats = addTrackingCategory(s,options)endif options.mainsuffixAfterIcon and options.mainsuffixAfterIcon ~= '' then   -- another suffix but after wikidata icons =  s .. options.mainsuffixAfterIcon endelse     if options.NosValue and options.NosValue ~= '' then -- value if no local value and no wikidata value      s = options.NosValue    endend    if options.returnnumberofvalues and (options.returnnumberofvalues ~= "" or options.returnnumberofvalues == true ) then--mw.log( "valuesnumb: " .. valuesnumb )         return s , valuesnumb    end    return sendfunction p.isSubclass(frame)if frame.args then Frame_args = frame.args endreturn 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 '' endif frame.args then Frame_args = frame.args endlocal site = frame.args[2] or frame.args.sitelocal id = frame.args[1] or frame.args.idlocal count = frame.args.countsitelinksif not id or id == "" thenif frame.args.page and frame.args.page ~= "" thenid = mw.wikibase.getEntityIdForTitle( frame.args.page )endendif count and count ~= "" then return countSiteLinks(id)end    local link = sitelink( id , site )    if link and link ~= ''  then        return linkendendfunction p.getSiteLink1(frame)if frame.args then Frame_args = frame.args endlocal project = frame.args[1] local id = frame.args[2]local link = sitelink( id , project )var = linkreturn varend-- returns the page id (Q...) of the current page or nothing of the page is not connected to Wikidatafunction p.pageId(frame)return  mw.wikibase.getEntityIdForCurrentPage()endfunction p.descriptionIn(frame)if frame.args then Frame_args = frame.args endlocal langcode = frame.args[1] or frame.args["lang"]local id = frame.args[2]  or frame.args["id"]return descriptionIn( langcode ,id  )endfunction p.labelIn(frame)if frame.args then Frame_args = frame.args endlocal langcode = frame.args[1]local id = frame.args[2] -- "id" must be nil, as access to other Wikidata objects is disabled in Mediawiki configurationreturn labelIn( langcode ,id  )endfunction p.ViewSomething(frame)   -- from en:Module:Wikidataif frame.args then Frame_args = frame.args endlocal 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 endlocal data = mw.wikibase.getEntityObject(aa)if not data thenreturn nilendlocal i = 1while true dolocal index = f.args[i]if not index thenif type(data) == "table" thenreturn mw.text.jsonEncode(data, mw.text.JSON_PRESERVE_KEYS + mw.text.JSON_PRETTY)elsereturn tostring(data)endenddata = data[index] or data[tonumber(index)]if not data thenreturnendi = i + 1endendfunction p.Dump(frame)if frame.args then Frame_args = frame.args endlocal 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 endlocal data = mw.wikibase.getEntityObject(aa)if not data thenreturn i18n.warnDumpendlocal i = 1while true dolocal index = f.args[i]if not index thenreturn frame:extensionTag("source", mw.dumpObject(data),{ lang= 'lua'}).. i18n.warnDumpenddata = data[index] or data[tonumber(index)]if not data thenreturn i18n.warnDumpendi = i + 1endendfunction p.countSiteLinks(id)return countSiteLinks(id)endfunction p.EntityIdForTitle(frame)if frame.args then Frame_args = frame.args endlocal title = frame.args[1]local str = mw.wikibase.getEntityIdForTitle( title )--mw.log(str)return strendreturn p