-- Master version: [[:ca:Module:Wikidata]]-- compatible version 20180115localp={}localwiki={langcode=mw.language.getContentLanguage().code}------------------------------------------------------------------------------- internationalisation at [[Module:Wikidata/i18n]]locali18n={["errors"]={["property-not-found"]="Property not found.",["entity-not-found"]="Wikidata entity not found.",["unknown-claim-type"]="Unknown claim type.",["unknown-entity-type"]="Unknown entity type.",["qualifier-not-found"]="Qualifier not found.",["site-not-found"]="Wikimedia project not found.",["unknown-datetime-format"]="Unknown datetime format.",["local-article-not-found"]="Article is not yet available in this wiki.",['not-from-content-page']="Do not invoke from content page. Use a template or use a module subpage like /sandbox for testing."},["datetime"]={-- $1 is a placeholder for the actual number[0]="$1 billion years",-- precision: billion years[1]="$100 million years",-- precision: hundred million years[2]="$10 million years",-- precision: ten million years[3]="$1 million years",-- precision: million years[4]="$100,000 years",-- precision: hundred thousand years[5]="$10,000 years",-- precision: ten thousand years[6]="$1 millennium",-- precision: millennium[7]="$1 century",-- precision: century[8]="$1s",-- precision: decade-- the following use the format of #time parser function[9]="Y",-- precision: year, [10]="F Y",-- precision: month[11]="F j, Y",-- precision: day[12]="F j, Y ga",-- precision: hour[13]="F j, Y g:ia",-- precision: minute[14]="F j, Y g:i:sa",-- precision: second["beforenow"]="$1 BCE",-- how to format negative numbers for precisions 0 to 5["afternow"]="$1 CE",-- how to format positive numbers for precisions 0 to 5["bc"]='$1 "BCE"',-- how print negative years["ad"]="$1",-- how print positive years["bc-addon"]=" BC",-- suffix for negative dates["ad-addon"]=""-- suffix for 1st century AD dates},["monolingualtext"]='<span lang="%language">%text</span>',["warnDump"]="[[Category:Called function 'Dump' from module Wikidata]]",["cite"]={-- Cite web parameters["url"]="url",["title"]="title",["website"]="website",["access-date"]="access-date",["archive-url"]="archive-url",["archive-date"]="archive-date",["author"]="author",["publisher"]="publisher",["quote"]="quote",["language"]="language",["date"]="date",["pages"]="pages"}}localfunctiontrack(key)localframe=mw.getCurrentFrame()pcall(frame.expandTemplate,frame,{title='track/'..key})endlocalcases={}-- functions for local grammatical cases defined at [[Module:Wikidata/i18n]]------------------------------------------------------------------------------ module local functions-- Credit to http://stackoverflow.com/a/1283608/2644759-- cc-by-sa 3.0localfunctiontableMerge(t1,t2)fork,vinpairs(t2)doiftype(v)=="table"theniftype(t1[k]orfalse)=="table"thentableMerge(t1[k]or{},t2[k]or{})elset1[k]=vendelset1[k]=vendendreturnt1endlocalfunctionloadI18n()localexist,res=pcall(require,"Module:Wikidata/i18n")ifexistandnext(res)~=nilthentableMerge(i18n,res.i18n)cases=res.casesendendloadI18n()localfunctioncase(word,localcase)ifword==nilorword==''orcases[localcase]==nilthenreturnwordendreturncases[localcase](word)endlocalfunctionexpandBraces(text)iftext==nilthenreturntextendiftype(text)~="string"thentext=tostring(text)endforbracesinmw.ustring.gmatch(text,"{{(.-)}}")dolocalparts=mw.text.split(braces,"|")localtitle_part=parts[1]localparameters={}fori=2,#partsdoifmw.ustring.find(parts[i],"=")thenlocalsubparts=mw.text.split(parts[i],"=")parameters[subparts[1]]=subparts[2]elsetable.insert(parameters,parts[i])endendlocalbraces_expandedifmw.ustring.find(title_part,":")thenbraces_expanded=mw.getCurrentFrame():callParserFunction{name=title_part,args=parameters}elsebraces_expanded=mw.getCurrentFrame():expandTemplate{title=title_part,args=parameters}endbraces=mw.ustring.gsub(braces,"([%^%$%(%)%%%.%[%]%*%+%-%?])","%%%1")-- escape magic characterstext=mw.ustring.gsub(text,"{{"..braces.."}}",braces_expanded)endreturntextendlocalfunctionprintDatavalueString(data,parameters)ifparameter=='weblink'thenreturn'['..data..' '..mw.text.split(data,'//')[2]..']'elseifmw.ustring.find((parameters.formattingor''),'$1',1,true)then-- formatting = a patternlocalescaped_data=mw.ustring.gsub(data,"%%","%%%")-- escape % character, normally used in url, avoiding invalid capture in gsubreturnexpandBraces(mw.ustring.gsub(parameters.formatting,'$1',escaped_data))elseifparameters.casethenreturncase(data,parameters.case)elsereturndataendendlocalfunctionprintDatavalueCoordinate(data,parameter)ifparameter=='latitude'thenreturndata.latitudeelseifparameter=='longitude'thenreturndata.longitudeelseifparameter=='dimension'thenreturndata.dimensionelse--default formatting='globe'ifdata.globe==''ordata.globe==nilordata.globe=='http://www.wikidata.org/entity/Q2'thenreturn'earth'elselocalglobenum=mw.text.split(data.globe,'entity/')[2]-- http://www.wikidata.org/wiki/Q2localglobetable={Q3134='callisto',Q596='ceres',Q15040='dione',Q3303='enceladus',Q3143='europa',Q17975='phoebe',Q3169='ganymede',Q3123='io',Q17958='iapetus',Q405='moon',Q111='mars',Q308='mercury',Q15034='mimas',Q15050='rhea',Q15047='tethys',Q2565='titan',Q3359='triton',Q313='venus',Q3030='vesta'}ifglobetable[globenum]thenreturnglobetable[globenum]elsereturnglobenumendendendendlocalfunctionprintDatavalueQuantity(data,parameter)-- exemples: 277±1 Centímetre, 1,94 metrelocalamount=data.amountamount=mw.ustring.gsub(amount,"%+","")localsortkey=string.format("%09d",amount)locallang=mw.language.new(wiki.langcode)amount=lang:formatNum(tonumber(amount))-- This is used to get the unit name for a numeric valuelocalsuffix=""ifparameter=="unit"orparameter=="unitcode"then-- get the url for the unit entry on Wikidata:localunitID=data.unit-- and just return the last bit from "Q" to the end (which is the QID):unitID=mw.ustring.sub(unitID,mw.ustring.find(unitID,"Q"),-1)ifmw.ustring.sub(unitID,1,1)=="Q"thenlocalunit_label=mw.wikibase.label(unitID)suffix=" "..require("Module:Wikidata/Units").getUnit(amount,unit_label,unitID,parameter=="unitcode")endendreturnamount..suffix,sortkeyendlocalfunctionprintDatavalueTime(data,parameter)-- Dates and times are stored in ISO 8601 formatlocaltimestamp=data.timelocalsortkey=timestamplocaladdon=""-- check for negative date, ex. "-0027-01-16T00:00:00Z"ifstring.sub(timestamp,1,1)=='-'thentimestamp='+'..string.sub(timestamp,2)addon=i18n.datetime["bc-addon"]elseifstring.sub(timestamp,2,3)=='00'thenaddon=i18n.datetime["ad-addon"]endlocalfunctiond(f,t)returnmw.language.new(wiki.langcode):formatDate(f,tortimestamp)..addonendlocalprecision=data.precisionor11localintyear=tonumber(mw.ustring.match(timestamp,"^\+?%d+"))localret=""-- precision is 10000 years or moreifprecision<=5thenlocalfactor=10^((5-precision)+4)localy2=math.ceil(math.abs(intyear)/factor)localrelative=mw.ustring.gsub(i18n.datetime[precision],"$1",tostring(y2))ifaddon==i18n.datetime["bc-addon"]then-- negative dateret=mw.ustring.gsub(i18n.datetime.beforenow,"$1",relative)elseret=mw.ustring.gsub(i18n.datetime.afternow,"$1",relative)end-- precision is millennia, centuries or decadeselseifprecision==6thenlocalcard=math.floor((intyear-1)/1000)+1ifmw.ustring.find(i18n.datetime[6],"$1")thenret=mw.ustring.gsub(i18n.datetime[6],"$1",tostring(card))..addonelseret=d(i18n.datetime[6],string.format("%04d",tostring(card)))endelseifprecision==7thenlocalcard=math.floor((math.abs(intyear)-1)/100)+1ifmw.ustring.find(i18n.datetime[7],"$1")thenret=mw.ustring.gsub(i18n.datetime[7],"$1",tostring(card))..addonelseret=d(i18n.datetime[7],string.format("%04d",tostring(card)))endelseifprecision==8thenlocalcard=math.floor(math.abs(intyear)/10)*10ret=mw.ustring.gsub(i18n.datetime[8],"$1",tostring(card))..addon-- precision is yearelseifparameter=='Y'orprecision==9thenret=tostring(intyear)..addon-- precision is monthelseifprecision==10thentimestamp=timestamp.." + 1 day"-- formatDate yyyy-mm-00 returns the previous monthret,_=string.gsub(d(i18n.datetime[10])," 0+"," ")-- supress leading zeros in yearelseifparameterthenret,_=string.gsub(d(parameter),"([ %[])0+","%1")-- supress leading zeros in year optionally linkedelse-- ret, _ = string.gsub(d(i18n.datetime[11]), " 0+", " ")-- TODO: move localized function to /i18nret=require("Module:Date").genitive_year(intyear)..d(' F"k" j')endreturnret,sortkeyendlocalfunctionprintDatavalueEntity(data,parameters)localentityId="Q"..tostring(data['numeric-id'])locallabel,lang=mw.wikibase.getLabelWithLang(entityId)localsitelink=mw.wikibase.sitelink(entityId)localparameter=parameters.formattinglocallabelcase=labelorsitelinkifparameters.casethenlabelcase=case(labelcase,parameters.case,lang)endlocalret1,ret2ifparameter=='raw'thenret1=entityIdret2=entityIdelseifparameter=='label'thenret1=labelcaseorentityIdret2=labelcaseorentityIdelseifparameter=='sitelink'thenret1=(sitelinkor'wikidata:'..entityId)ret2=sitelinkorentityIdelseifmw.ustring.find((parameteror''),'$1',1,true)then-- formatting = a patternret1=mw.ustring.gsub(parameter,'$1',labelcaseorentityId)ret1=expandBraces(ret1)ret2=labelcaseorentityIdelseifparameter=="ucfirst"orparameter=="ucinternallink"thenlabelcase=labelcaseandmw.language.getContentLanguage():ucfirst(labelcase)-- only first of a list, reset formatting for next onesifparameter=="ucinterlanllink"thenparameters.formatting='internallink'elseparameters.formatting=nil-- default formattrack("wikidata/ucfirst")endendifsitelinkthenret1='[['..sitelink..'|'..labelcase..']]'ret2=labelcaseelseiflabelandparameter=='internallink'orparameter=='ucinternallink'thenret1='[['..label..'|'..labelcase..']]'ret2=labelcaseelseret1='[[wikidata:'..entityId..'|'..(labelcaseorentityId)..']]'ret2=labelcaseorentityIdendendreturnret1,ret2endlocalfunctionprintDatavalueMonolingualText(data,parameter)-- data fields: language [string], text [string]localresult=nilifparameter=="language"orparameter=="text"thenresult=data[parameter]elseifparameterthenifdata["language"]==wiki.langcodethenresult=data["text"]endelseresult=mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext,"%%language",data["language"]),"%%text",data["text"])endreturnresultendlocalfunctionprintDatatypeMath(data)returnmw.getCurrentFrame():callParserFunction('#tag:math',data)endlocalfunctionprintError(key)return'<span class="error">'..i18n.errors[key]..'</span>'end-- the "qualifiers" and "snaks" field have a respective "qualifiers-order" and "snaks-order" field-- use these as the second parameter and this function instead of the built-in "pairs" function-- to iterate over all qualifiers and snaks in the intended order.localfunctionorderedpairs(array,order)ifnotorderthenreturnpairs(array)end-- return iterator functionlocali=0returnfunction()i=i+1iforder[i]thenreturnorder[i],array[order[i]]endendendlocalfunctionfindClaims(entity,property)ifnotpropertyornotentityornotentity.claimsthenreturnendifnotmw.ustring.match(property,"^P%d+$")then-- get property id for the given labelproperty=mw.wikibase.resolvePropertyId(property)ifnotpropertythenreturnendendreturnentity.claims[property]endlocalfunctiongetSnakValue(snak,parameters)localparameter=parameters.formattingifsnak.snaktype=='value'then-- call the respective snak parserifsnak.datatype=='math'thenreturnprintDatatypeMath(snak.datavalue.value)elseifsnak.datavalue.type=="string"thenreturnprintDatavalueString(snak.datavalue.value,parameters)elseifsnak.datavalue.type=="globecoordinate"thenreturnprintDatavalueCoordinate(snak.datavalue.value,parameter)elseifsnak.datavalue.type=="quantity"thenreturnprintDatavalueQuantity(snak.datavalue.value,parameter)elseifsnak.datavalue.type=="time"thenreturnprintDatavalueTime(snak.datavalue.value,parameter)elseifsnak.datavalue.type=='wikibase-entityid'thenreturnprintDatavalueEntity(snak.datavalue.value,parameters)elseifsnak.datavalue.type=='monolingualtext'thenreturnprintDatavalueMonolingualText(snak.datavalue.value,parameter)endendreturnmw.wikibase.renderSnak(snak)endlocalfunctiongetQualifierSnak(claim,qualifierId,parameters)-- a "snak" is Wikidata terminology for a typed key/value pair-- a claim consists of a main snak holding the main information of this claim,-- as well as a list of attribute snaks and a list of references snaksifqualifierIdthen-- search the attribute snak with the given qualifier as keyifclaim.qualifiersthenlocalqualifier=claim.qualifiers[qualifierId]ifqualifierthen-- iterate over monolingualtext qualifiers to get local languageforidxinpairs(qualifier)doifqualifier[idx].datavalueandqualifier[idx].datavalue.valueandqualifier[idx].datavalue.value.languagethenifqualifier[idx].datavalue.value.language==wiki.langcodethenreturnqualifier[idx]endendendifparameters.listthenreturnqualifierelsereturnqualifier[1]endendendreturnnil,printError("qualifier-not-found")else-- otherwise return the main snakreturnclaim.mainsnakendendlocalfunctiongetValueOfClaim(claim,qualifierId,parameters)localerrorlocalsnaksnak,error=getQualifierSnak(claim,qualifierId,parameters)ifnotsnakthenreturnnil,nil,errorelseifsnak[1]then-- a multi qualifierlocalresult={}localsortkey={}foridxinpairs(snak)doresult[#result+1],sortkey[#sortkey+1]=getSnakValue(snak[idx],parameters)endreturnmw.text.listToText(result,parameters.qseparator,parameters.qconjunction),sortkey[1]else-- a property or a qualifierreturngetSnakValue(snak,parameters)endendlocalfunctiongetReferences(claim)localrefaliases={citeWeb="Q6925554",author="P50",publisher="P123",importedFrom="P143",statedIn="P248",pages="P304",publicationDate="P577",startTime="P580",endTime="P582",chapter="P792",retrieved="P813",referenceURL="P854",archiveURL="P1065",title="P1476",quote="P1683",shortName="P1813",language="P2439",archiveDate="P2960"}localresult=""-- traverse through all referencesforrefinpairs(claim.referencesor{})dolocalrefpartslocalrefs={}-- traverse through all parts of the current referenceforsnakkey,snakvalinpairs(claim.references[ref].snaksor{})doifsnakkey~=refaliases.importedFromthen-- "imported from" is not a proper referenceforsnakidx=1,#snakvaldoifsnakidx>1thenrefparts=refparts..", "endrefparts=refpartsor''..getSnakValue(snakval[snakidx],{})endrefs[snakkey]=refpartsrefparts=nilendend-- get title of general template for citing web referenceslocaltemplate=mw.wikibase.sitelink(refaliases.citeWeb)or""template=mw.text.split(template,":")[2]-- split off namespace from front-- (1) if both "reference URL" and "title" are present, then use the general template for citing web referencesifrefs[refaliases.referenceURL]and(refs[refaliases.title]orrefs[refaliases.statedIn])andtemplatethenlocalciteParams={}citeParams[i18n['cite']['url']]=refs[refaliases.referenceURL]citeParams[i18n['cite']['title']]=refs[refaliases.title]orrefs[refaliases.statedIn]:match("^%[%[.-|(.-)%]%]")citeParams[i18n['cite']['website']]=refs[refaliases.statedIn]citeParams[i18n['cite']['language']]=refs[refaliases.language]citeParams[i18n['cite']['date']]=refs[refaliases.publicationDate]citeParams[i18n['cite']['access-date']]=refs[refaliases.retrieved]citeParams[i18n['cite']['archive-url']]=refs[refaliases.archiveURL]citeParams[i18n['cite']['archive-date']]=refs[refaliases.archiveDate]citeParams[i18n['cite']['publisher']]=refs[refaliases.publisher]citeParams[i18n['cite']['quote']]=refs[refaliases.quote]citeParams[i18n['cite']['pages']]=refs[refaliases.pages]citeParams[i18n['cite']['author']]=refs[refaliases.author]refparts=mw.getCurrentFrame():expandTemplate{title=template,args=citeParams}else-- raw ouputfork,vinorderedpairs(refsor{},claim.references[ref]["snaks-order"])doifkandvthenifrefpartsthenrefparts=refparts..", "elserefparts=""endrefparts=refparts..tostring(mw.wikibase.label(k))..": "refparts=refparts..vendendendifrefpartsthenresult=result..mw.getCurrentFrame():extensionTag("ref",refparts)endendreturnresultend-- Return the site link (for the current site) for a given data item.functionp.getSiteLink(frame)ifframe.args[1]==nilthenentity=mw.wikibase.getEntityObject()ifnotentitythenreturnnilendid=entity.idelseid=frame.args[1]endreturnmw.wikibase.sitelink(id)end-- On debug console use: =p._debug({item="Q...", property="P...", ...})functionp._debug(args)returnp._main(args)endfunctionp.claim(frame)--if mw.title.new(frame:getParent():getTitle()).isContentPage and not mw.title.new(frame:getTitle()).isSubpage then-- -- invoked from a content page and not invoking a module subpage-- return printError("not-from-content-page")--endreturnp._main(frame.args)endfunctionp._main(args)--If a value is already set, use itifargs.valueandargs.value~=''thenreturnargs.valueend-- argumentslocalproperty=string.upper(args["property"]or"")localid=args["item"];ifid==""thenid=nilendlocalidgender=args["itemgender"]ifidgenderandnotstring.match(idgender,"^Q%d+$")then-- id malformed, maybe "unknown value"idgender=nilendlocalqualifierId={}qualifierId[1]=args["qualifier"]andstring.upper(args["qualifier"])ornillocali=2whileargs["qualifier"..i]doqualifierId[i]=string.upper(args["qualifier"..i])i=i+1endlocalparameter=args["formatting"]or'';ifparameter==""thenparameter=nilendlocalcase=args.caselocallist=args["list"]ortrue;iflist=="false"thenlist=falseendlocalsorting_col=args.tablesortlocalsorting_up=(args.sortingor"")~="-1"localseparator=args.separatorlocalconjunction=args.conjunctionorargs.separatorlocalrowformat=args.rowformatlocalreferences=args["references"]localshowerrors=args["showerrors"]localdefault=args["default"]ifargs["rank"]andargs["rank"]~=''thenlist=falseend-- compatibilitat de transicióifargs["rank"]thentrack("wikidata/rank")endlocalparameters={["formatting"]=parameter,["list"]=list,["case"]=case,["separator"]=separator,["conjunction"]=conjunction,["qseparator"]=separator,["qconjunction"]=conjunction}localpreformat=""localpostformat=""ifparameters.formatting=="table"thenparameters.separator=parameters.separatoror"<br />"parameters.conjunction=parameters.conjunctionor"<br />"parameters.qseparator=", "parameters.qconjunction=", "ifnotrowformatthenrowformat="$0 ($1"i=2whilequalifierId[i]dorowformat=rowformat..", $"..ii=i+1endrowformat=rowformat..")"elseifmw.ustring.find(rowformat,"^[*#]")thenparameters.separator="</li><li>"parameters.conjunction="</li><li>"ifmw.ustring.match(rowformat,"^[*#]")=="*"thenpreformat="<ul><li>"postformat="</li></ul>"elsepreformat="<ol><li>"postformat="</li></ol>"endrowformat=mw.ustring.gsub(rowformat,"^[*#] ?","")endendifdefaultthenshowerrors=nilend-- get wikidata entitylocalentity=mw.wikibase.getEntityObject(id)ifnotentitythenifshowerrorsthenreturnprintError("entity-not-found")elsereturndefaultendend-- fetch the first claim of satisfying the given propertylocalclaims=findClaims(entity,property)ifnotclaimsornotclaims[1]thenifshowerrorsthenreturnprintError("property-not-found")elsereturndefaultendend-- find feminine case if gender is requestedlocalgenderCaseifparameters.case=="gender"oridgenderorparameters.formatting=="table"thenlocalgenderEntity=idgenderandmw.wikibase.getEntityObject(idgender)orentitylocalgenderClaims=genderEntity.claims["P21"]ifgenderClaimsthenlocalgenderId=getValueOfClaim(genderClaims[1],nil,{["formatting"]="raw"})ifgenderId=="Q6581072"orgenderId=="Q1052281"orgenderId=="Q43445"then-- female, transgender female, female organismgenderCase=(parameters.case=="infoboxlabel")and"labelfeminine"or"feminine"ifparameters.case=="gender"oridgenderthenparameters.case=genderCaseendendendend-- get initial sort indiceslocalsortindices={}foridxinpairs(claims)dosortindices[#sortindices+1]=idxend-- sort by claim ranklocalcomparator=function(a,b)localrankmap={deprecated=2,normal=1,preferred=0}localranka=rankmap[claims[a].rankor"normal"]..string.format("%08d",a)localrankb=rankmap[claims[b].rankor"normal"]..string.format("%08d",b)returnranka<rankbendtable.sort(sortindices,comparator)localresultlocalerrorifparameters.listorparameters.formatting=="table"then-- convert LF to line feed, <br /> may not work on some casesparameters.separator=parameters.separator=="LF"and"\010"orparameters.separatorparameters.conjunction=parameters.conjunction=="LF"and"\010"orparameters.conjunction-- iterate over all elements and return their value (if existing)localvalue,valueqlocalsortkey,sortkeyqlocalvalues={}localsortkeys={}localfirstrank=parameters.list=="firstrank"andclaims[sortindices[1]].rankor''foridxinpairs(claims)dolocalclaim=claims[sortindices[idx]]iffirstrank~=''andfirstrank~=claim.rankthenbreakendvalues[#values+1]={}sortkeys[#sortkeys+1]={}ifparameters.formatting=="table"thenlocalparams=mw.clone(parameters)params.formatting=args["colformat0"]ifargs["case0"]thenparams.case=args["case0"]=="gender"andgenderCaseorargs["case0"]endvalue,sortkey,error=getValueOfClaim(claim,nil,params)fori,qualinipairs(qualifierId)doparams.formatting=args["colformat"..i]ifargs["case"..i]thenparams.case=args["case"..i]=="gender"andgenderCaseorargs["case"..i]elseparams.case=parameters.caseendvalueq,sortkeyq,_=getValueOfClaim(claim,qual,params)values[#values]["col"..i]=valueqsortkeys[#sortkeys]["col"..i]=sortkeyqorvalueqendelsevalue,sortkey,error=getValueOfClaim(claim,qualifierId[1],parameters)endifnotvalueandshowerrorsthenvalue=errorendifvalueandreferencesthenvalue=value..getReferences(claim)endvalues[#values]["col0"]=valuesortkeys[#sortkeys]["col0"]=sortkeyorvalueend-- sort and format resultssortindices={}foridxinpairs(values)dosortindices[#sortindices+1]=idxendifsorting_colthenlocalcomparator=function(a,b)localvaluea=sortkeys[a]["col"..sorting_col]or''localvalueb=sortkeys[b]["col"..sorting_col]or''ifsorting_upthenreturnvaluea<valuebendreturnvaluea>valuebendtable.sort(sortindices,comparator)endresult={}foridxinpairs(values)dolocalvaluerow=values[sortindices[idx]]value=valuerow["col0"]ifparameters.formatting=="table"thenvalue=mw.ustring.gsub(rowformat.."$","$0",value)-- fake end character added for easy gsubfori,_inipairs(qualifierId)dovalueq=valuerow["col"..i]ifargs["rowsubformat"..i]andvalueqthen-- add fake end character $-- gsub $i not followed by a number so $1 doesn't match $10, $11...-- remove fake end charactervalueq=mw.ustring.gsub(args["rowsubformat"..i].."$","$"..i.."(%D)",valueq.."%1")valueq=string.sub(valueq,1,-2)endvalue=mw.ustring.gsub(value,"$"..i.."(%D)",(valueqor'').."%1")endvalue=string.sub(value,1,-2)-- remove fake end characterendvalue=expandBraces(value)result[#result+1]=valueendresult=preformat..mw.text.listToText(result,parameters.separator,parameters.conjunction)..postformatelse-- return first elementlocalclaim=claims[sortindices[1]]result,_,error=getValueOfClaim(claim,qualifierId[1],parameters)ifresultandreferencesthenresult=result..getReferences(claim)endendifresultthenreturnresultelseifshowerrorsthenreturnerrorelsereturndefaultendendend-- Return the statements with a formatfunctionp.formatStatements(frame)track("wikidata/formatStatements")returnp.claim(frame)-- compatibilitat de transicióend-- This is used to get the TA98 (Terminologia Anatomica first edition 1998) values like 'A01.1.00.005' (property P1323)-- which are then linked to http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/01.1.00.005%20Entity%20TA98%20EN.htm-- uses the newer mw.wikibase calls instead of directly using the snaks-- formatPropertyValues returns a table with the P1323 values concatenated with ", " so we have to split them out into a table in order to construct the return stringp.getTAValue=function(frame)localent=mw.wikibase.getEntityObject()localprops=ent:formatPropertyValues('P1323')localout={}localt={}fork,vinpairs(props)doifk=='value'thent=mw.text.split(v,", ")fork2,v2inpairs(t)doout[#out+1]="[http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/"..string.sub(v2,2).."%20Entity%20TA98%20EN.htm "..v2.."]"endendendlocalret=table.concat(out,"<br> ")if#ret==0thenret="Invalid TA"endreturnretend-- look into entity objectfunctionp.ViewSomething(frame)localf=(frame.args[1]orframe.args.item)andframeorframe:getParent()localid=f.args.itemifidand(#id==0)thenid=nilendlocaldata=mw.wikibase.getEntityObject(id)ifnotdatathenreturnnilendlocali=1whiletruedolocalindex=f.args[i]ifnotindextheniftype(data)=="table"thenreturnframe:extensionTag('syntaxhighlight',mw.text.jsonEncode(data,mw.text.JSON_PRETTY),{lang='json'})elsereturntostring(data)endenddata=data[index]ordata[tonumber(index)]ifnotdatathenreturnendi=i+1endend-- Dump data tree structure-- From pl:Module:Wikidane, by User:Paweł Ziemian-- Funció pensada com a eina d'ajuda en previsualització.functionp.Dump(frame)localdata=mw.wikibase.getEntityObject()ifnotdatathenreturni18n.warnDumpendlocalf=frame.args[1]andframeorframe:getParent()locali=1whiletruedolocalindex=f.args[i]ifnotindexthenreturnframe:extensionTag('syntaxhighlight',mw.dumpObject(data),{lang='json'})..i18n.warnDumpenddata=data[index]ordata[tonumber(index)]ifnotdatathenreturni18n.warnDumpendi=i+1endend-- Look into entity object-- From pl:Module:Wikidane, function V, by User:Paweł Ziemianfunctionp.getEntityFromTree(frame)localdata=mw.wikibase.getEntityObject()ifnotdatathenreturnnilendlocalf=frame.args[1]andframeorframe:getParent()locali=1whiletruedolocalindex=f.args[i]ifnotindexthenreturntostring(data)enddata=data[index]ordata[tonumber(index)]ifnotdatathenreturnendi=i+1endend-- getParentValues: returns a property value with its instance label fetching a recursive treelocalfunctionuc_first(word)returnmw.ustring.upper(mw.ustring.sub(word,1,1))..mw.ustring.sub(word,2)endlocalfunctiongetPropertyValue(id,property,parameter)localentity=mw.wikibase.getEntityObject(id)ifnot(entityandentity.claims)thenreturnendlocalclaims=entity.claims[property]ifnotclaimsthenreturnend-- get initial sort indiceslocalsortindices={}foridxinpairs(claims)dosortindices[#sortindices+1]=idxend-- sort by claim ranklocalcomparator=function(a,b)localrankmap={deprecated=2,normal=1,preferred=0}localranka=rankmap[claims[a].rankor"normal"]..string.format("%08d",a)localrankb=rankmap[claims[b].rankor"normal"]..string.format("%08d",b)returnranka<rankbendtable.sort(sortindices,comparator)localsnak=claims[sortindices[1]].mainsnaklocalentityIdlocalresult='-'-- default for 'no value'ifsnak.datavaluethenentityId="Q"..tostring(snak.datavalue.value['numeric-id'])result,_=getSnakValue(snak,{formatting=parameter})endreturnentityId,resultendfunctionp.getParentValues(frame)localargs=frame.argslocalid=args["item"];ifid==""thenid=nilendlocalpropertySup=args["property"];if(propertySup==nilorpropertySup=="")thenpropertySup="P131"end--administrative entitylocalpropertyLabel=args["label"];if(propertyLabel==nilorpropertyLabel=="")thenpropertyLabel="P31"end--instancelocalpropertyLink=args["valuetext"];ifpropertyLink==""thenpropertyLink=nilend--internallinklocalupto=args["upto"];ifupto==""thenupto=nilendlocallabelShow=args["labelshow"];iflabelShow==""thenlabelShow=nilendlocalrowformat=args["rowformat"];if(rowformat==nilorrowformat=="")thenrowformat="$0 = $1"endlocalseparator=args["separator"];if(separator==nilorseparator=="")thenseparator="<br />"endlocalsorting=args["sorting"];ifsorting==""thensorting=nilendlocallastlabel=uc_first(uptoor'')localmaxloop=tonumber(upto)or(lastlabel==''and10or50)locallabelFilter={}iflabelShowthenfori,vinipairs(mw.text.split(labelShow,"/"))dolabelFilter[uc_first(v)]=trueendendlocalresult={}locallabel,link,linktextforiter=1,maxloopdolocallabel,linkid,link=getPropertyValue(id,propertySup,"internallink")ifidthen_,label=getPropertyValue(id,propertyLabel,"label")iflabelandlinkthenifpropertyLinkthen_,linktext=getPropertyValue(id,propertyLink,"label")iflinktextthenlink=mw.ustring.gsub(link,"%[%[(.*)%|.+%]%]","[[%1|"..linktext.."]]")endendlabel=case(label,"infoboxlabel")iflabelShow==nilorlabelFilter[label]thenresult[#result+1]={label,link}labelFilter[label]=nil-- only first label foundendiflabel==lastlabelthenbreakendelsebreakendelsebreakendendlocalret={}localfirst=1locallast=#resultlocaliter=1ifsorting=="-1"thenfirst=#result;last=1;iter=-1endfori=first,last,iterdolocalrowtext=mw.ustring.gsub(rowformat,"$[01]",{["$0"]=result[i][1],["$1"]=result[i][2]})ret[#ret+1]=expandBraces(rowtext)endreturnmw.text.listToText(ret,separator,separator)endfunctionp.linkWithParentLabel(frame)localargs={}fork,vinpairs(frame.args)do-- metatableargs[k]=vendargs.list="true"args.formatting="internallink"args.separator="/·/"locallink=p._main(args)-- get internal link of property/qualifierifitems_list==nilthenreturnendlocallink_table=mw.text.split(link_list,"/·/",true)args.formatting="raw"localitems_list=p._main(args)-- get item of property/qualifierlocalitems_table=mw.text.split(items_list,"/·/",true)args.property=args.parentargs.qualifier=nilargs.formatting="label"args.list="false"fori,vinipairs(items_table)doargs.item=vlocallink_label=p._main(args)-- get label of parent propertyiflink_labelthenlink_table[i]=mw.ustring.gsub(link_table[1]or'',"%[%[(.*)%|.+%]%]","[[%1|"..link_label.."]]")endendreturnmw.text.listToText(link_table)endfunctionp.years_old(frame)localargs=frame.argslocalid=args.item;ifid==''thenid=nilendlocallang=mw.language.new('en')localfunctionfetchsnak(id,snak)localret=mw.wikibase.getEntityObject(id)fori,vinipairs(snak)doifret==nilthenbreakendret=ret[v]endreturnretendlocalbirth=fetchsnak(id,{'claims','P569',1,'mainsnak','datavalue','value'})iftype(birth)~='table'orbirth.time==nilorbirth.precision==nilorbirth.precision<8thenreturnendlocaldeath=fetchsnak(args.item,{'claims','P570',1,'mainsnak','datavalue','value'})iftype(death)~='table'ordeath.time==nilordeath.precision==nilthendeath={['time']=lang:formatDate('c'),['precision']=11}-- current dateelseifdeath.precision<8thenreturnendlocaldates={}dates[1]={['min']={},['max']={},['precision']=birth.precision}dates[1].min.year=tonumber(mw.ustring.match(birth.time,"^[+-]?%d+"))dates[1].min.month=tonumber(mw.ustring.match(birth.time,"\-(%d%d)\-"))dates[1].min.day=tonumber(mw.ustring.match(birth.time,"\-(%d%d)T"))dates[1].max=mw.clone(dates[1].min)dates[2]={['min']={},['max']={},['precision']=death.precision}dates[2].min.year=tonumber(mw.ustring.match(death.time,"^[+-]?%d+"))dates[2].min.month=tonumber(mw.ustring.match(death.time,"\-(%d%d)\-"))dates[2].min.day=tonumber(mw.ustring.match(death.time,"\-(%d%d)T"))dates[2].max=mw.clone(dates[2].min)fori,dinipairs(dates)doifd.precision==10then-- monthd.min.day=1localtimestamp=string.format("%04d",tostring(math.abs(d.max.year)))..string.format("%02d",tostring(d.max.month)).."01"d.max.day=tonumber(lang:formatDate("j",timestamp.." + 1 month - 1 day"))elseifd.precision<10then-- year or decaded.min.day=1d.min.month=1d.max.day=31d.max.month=12ifd.precision==8then-- decaded.max.year=d.max.year+9endendendlocalfunctionage(d1,d2)localyears=d2.year-d1.yearifd2.month<d1.monthor(d2.month==d1.monthandd2.day<d1.day)thenyears=years-1endifd2.year>0andd1.year<0thenyears=years-1-- no year 0endreturnyearsendlocalold_min=age(dates[1].max,dates[2].min)localold_max=age(dates[1].min,dates[2].max)localold=old_min==old_maxandold_minorold_min.."/"..old_maxifargs.formattingthenold=mw.ustring.gsub(args.formatting,'$1',old)endreturnoldendreturnp