Jump to content

Module:Commons link

From Simple English Wikipedia, the free encyclopedia

Documentation for this module may be created at Module:Commons link/doc

-- Module to find commons galleries and categories based on wikidata entrieslocalgetArgs=require('Module:Arguments').getArgslocalp={}-- Check if string is a valid QID-- Argument: QID to check-- Returns: valid (bool)localfunction_validQID(qid)returnqidandmw.ustring.find(qid,"^[Qq]%d+$")end-- Check if string is a valid wikidata property string-- Argument: property string to check-- Returns: valid (bool)localfunction_validProp(prop)returnpropandmw.ustring.find(prop,"^[Pp]%d+$")endfunction_lcfirst(doit,s)ifdoitthenreturnmw.ustring.lower(mw.ustring.sub(s,1,1))..mw.ustring.sub(s,2)endreturnsendlocalfunctionwarning(msg)localframe=mw.getCurrentFrame():getParent()localhtml=""ifframe:preprocess("{{REVISIONID}}")==""thenhtml='<div style="color:red"><strong>Warning:</strong> '..msghtml=html..' <small>(this message is shown only in preview)</small></div>'endreturnhtmlend-- Get title, namespace, and QID for current page-- Arguments:-- qid = testing only: get title of alternative page with QID=qid-- nsQid = whether to return the ns of the qid page or current-- Returns:-- title, namespace (string), qid of current page (or test page)localfunction_getTitleQID(qid,nsQid)localtitleObject=mw.title.getCurrentTitle()-- look up qid for current page (if not testing)localnsText=mw.ustring.gsub(titleObject.nsText,"_"," ")ifnot_validQID(qid)thenqid=mw.wikibase.getEntityIdForCurrentPage()returntitleObject.text,nsText,qidend-- testing-only path: given a qid, determine title-- always use namespace from current page (to suppress tracking cat)qid=qid:upper()localtitle=mw.wikibase.getSitelink(qid)or""-- strip any namespace from sitelinklocalfirstColon=mw.ustring.find(title,':',1,true)localqidNsText=""iffirstColonthenqidNsText=mw.ustring.sub(title,1,firstColon-1)title=mw.ustring.sub(title,firstColon+1)endifnsQidthenreturntitle,qidNsText,qidendreturntitle,nsText,qidend-- Lookup Commons gallery in Wikidata-- Arguments:-- qid = QID of current article-- fetch = whether to lookup Commons sitelink (bool)-- commonsSitelink = default value for Commons sitelink-- Returns:-- categoryLink = name of Commons category, nil if nothing is found-- consistent = multiple wikidata fields are examined: are they consistent?-- commonsSitelink = commons sitelink for current articlelocalfunction_lookupGallery(qid,fetch,commonsSitelink)ifnot_validQID(qid)thenreturnnil,true,nilendqid=qid:upper()localgalleryLink=nillocalconsistent=true-- look up commons sitelink for article, use if not categoryiffetchthencommonsSitelink=mw.wikibase.getSitelink(qid,"commonswiki")orcommonsSitelinkendifcommonsSitelinkandmw.ustring.sub(commonsSitelink,1,9)~="Category:"thengalleryLink=commonsSitelinkend-- P935 is the "commons gallery" property for this articlelocalP935=mw.wikibase.getBestStatements(qid,"P935")[1]ifP935andP935.mainsnak.datavaluethenlocalgallery=P935.mainsnak.datavalue.valueifgalleryLinkandgalleryLink~=gallerythenconsistent=falseelsegalleryLink=galleryendendreturngalleryLink,consistent,commonsSitelinkend-- Find fallback category by looking up Commons sitelink of different page-- Arguments:-- qid = QID for current article-- property = property that refers to other article whose sitelink to return-- Returns: either category-stripped name of article, or nillocalfunction_lookupFallback(qid,property)ifnot_validQID(qid)ornot_validProp(property)thenreturnnilendqid=qid:upper()property=property:upper()-- If property exists on current article, get value (other article qid)localvalue=mw.wikibase.getBestStatements(qid,property)[1]ifvalueandvalue.mainsnak.datavalueandvalue.mainsnak.datavalue.value.idthen-- Look up Commons sitelink of other articlelocalsitelink=mw.wikibase.getSitelink(value.mainsnak.datavalue.value.id,"commonswiki")-- Check to see if it starts with "Category:". If so, strip it and returnifsitelinkandmw.ustring.sub(sitelink,1,9)=="Category:"thenreturnmw.ustring.sub(sitelink,10)endendreturnnilend-- Find Commons category by looking in wikidata-- Arguments:-- qid = QID of current article-- fetch = whether to lookup Commons sitelink (bool)-- commonsSitelink = default value for Commons sitelink-- Returns:-- categoryLink = name of Commons category, nil if nothing is found-- consistent = multiple wikidata fields are examined: are they consistent?-- commonsSitelink = commons sitelink for current articlelocalfunction_lookupCategory(qid,fetch,commonsSitelink)ifnot_validQID(qid)thenreturnnil,true,nilendqid=qid:upper()localcategoryLink=nillocalconsistent=true-- look up commons sitelink for article, use if starts with "Category:"iffetchthencommonsSitelink=mw.wikibase.getSitelink(qid,"commonswiki")orcommonsSitelinkendifcommonsSitelinkandmw.ustring.sub(commonsSitelink,1,9)=="Category:"thencategoryLink=mw.ustring.sub(commonsSitelink,10)end-- P373 is the "commons category" property for this articlelocalP373=mw.wikibase.getBestStatements(qid,"P373")[1]ifP373andP373.mainsnak.datavaluethenP373=P373.mainsnak.datavalue.valueifcategoryLinkandcategoryLink~=P373thenconsistent=falseqid=nil-- stop searching on inconsistent dataelsecategoryLink=P373endend-- P910 is the "topic's main category". Look for commons sitelink therelocalfallback=_lookupFallback(qid,"P910")iffallbackthenifcategoryLinkandcategoryLink~=fallbackthenconsistent=falseqid=nilelsecategoryLink=fallbackendend-- P1754 is the "list's main category". Look for commons sitelink therefallback=_lookupFallback(qid,"P1754")iffallbackthenifcategoryLinkandcategoryLink~=fallbackthenconsistent=falseelsecategoryLink=fallbackendendreturncategoryLink,consistent,commonsSitelinkend-- Does the article have a corresponding Commons gallery?-- Arguments:-- qid = QID to lookup in wikidata (for testing only)-- Returns:-- filename at Commons if so, nil if notfunctionp._hasGallery(qid)localwp_title,wp_nswp_title,wp_ns,qid=_getTitleQID(qid)localgalleryLink,consistent=_lookupGallery(qid,true)ifgalleryLinkandconsistentthenreturngalleryLinkendreturnnilend-- Does the article have a corresponding Commons category?-- Arguments:-- qid = QID to lookup in wikidata (for testing only)-- prefix = whether to add "Category:" to return string (default true)-- Returns:-- filename at Commons if so, blank if notfunctionp._hasCategory(qid,prefix)ifprefix==nilthenprefix=trueendlocalwp_title,wp_nswp_title,wp_ns,qid=_getTitleQID(qid)localcategoryLink,consistent=_lookupCategory(qid,true)ifcategoryLinkandconsistentthenifprefixthencategoryLink="Category:"..categoryLinkendreturncategoryLinkendreturnnilend-- Create Commons link corresponding to current article-- Arguments:-- namespace = namespace in Commons ("" for galleries)-- default = use as Commons link, don't access wikidata-- linktext = text to display in link-- search = string to search for-- fallback = string to search for if wikidata fails-- lcfirst = lower case the first letter in linktext-- qid = QID to lookup in wikidata (for testing only)-- Returns:-- formatted wikilink to Commons in specified namespacefunctionp._getCommons(namespace,default,linktext,search,fallback,lcfirst,qid)localnsColonifnotnamespaceornamespace==""thennsColon=""elsensColon=namespace..":"endifdefaultthenreturn"[[Commons:"..nsColon..default.."|".._lcfirst(lcfirst,linktextordefault).."]]"endifsearchthenreturn"[[Commons:Special:Search/"..nsColon..search.."|".._lcfirst(lcfirst,linktextorsearch).."]]"endlocalwp_title,wp_nswp_title,wp_ns,qid=_getTitleQID(qid)-- construct default result (which searches for title)localsearchResult="[[Commons:Special:Search/"..nsColon..(fallbackorwp_title)searchResult=searchResult.."|".._lcfirst(lcfirst,linktextorfallbackorwp_title).."]]"localcommonsLink=nillocalconsistent=trueifnsColon==""thencommonsLink,consistent=_lookupGallery(qid,true)elseifnamespace:lower()=="category"thencommonsLink,consistent=_lookupCategory(qid,true)end-- use wikidata if consistentifcommonsLinkandconsistentthenreturn"[[Commons:"..nsColon..commonsLink.."|".._lcfirst(lcfirst,linktextorcommonsLink).."]]"end-- if not consistent, fall back to search and add to tracking catifnotconsistentandwp_ns==""thenlocalfriendlyNSifnsColon==""thenfriendlyNS="gallery"elsefriendlyNS=namespace:lower()endsearchResult=searchResult.."[[Category:Inconsistent wikidata for Commons "..friendlyNS.."]]"endreturnsearchResultend-- Returns "best" Commons link: first look for gallery, then try category-- Arguments:-- default = use as Commons link, don't access wikidata-- linktext = text to display in link-- search = string to search for-- qid = QID to lookup in wikidata (for testing only)-- Returns:-- formatted wikilink to Commons "best" landing pagefunctionp._getGalleryOrCategory(default,linktext,search,fallback,qid)ifdefaultthenreturn"[[Commons:"..default.."|"..(linktextordefault).."]]"endifsearchthenreturn"[[Commons:Special:Search/"..search.."|"..(linktextorsearch).."]]"endlocalwp_title,wp_nswp_title,wp_ns,qid=_getTitleQID(qid)-- construct default result (which searches for title)localsearchResult="[[Commons:Special:Search/"..(fallbackorwp_title)searchResult=searchResult.."|"..(linktextorfallbackorwp_title).."]]"localtrackingCats=""localgalleryLink,consistent,commonsSitelink=_lookupGallery(qid,true)-- use wikidata if either sitelink or P935 exist, and they both agreeifgalleryLinkandconsistentthenreturn"[[Commons:"..galleryLink.."|"..(linktextorgalleryLink).."]]"endifnotconsistentandwp_ns==""thentrackingCats="[[Category:Inconsistent wikidata for Commons gallery]]"end-- if gallery is not good, fall back looking for categorylocalcategoryLinkcategoryLink,consistent=_lookupCategory(qid,false,commonsSitelink)ifcategoryLinkandconsistentthenreturn"[[Commons:Category:"..categoryLink.."|"..(linktextorcategoryLink).."]]"..trackingCatsendifnotconsistentandwp_ns==""thentrackingCats=trackingCats.."[[Category:Inconsistent wikidata for Commons category]]"endreturnsearchResult..trackingCatsend-- Make a string bold, italic, or both-- Arguments:-- s = string to format-- bold = make it bold-- italic = make it italic-- Returns:-- string modified with html tagslocalfunction_formatResult(s,bold,italic)localresultVal=""ifboldthenresultVal="<b>"endifitalicthenresultVal=resultVal.."<i>"endresultVal=resultVal..sifitalicthenresultVal=resultVal.."</i>"endifboldthenresultVal=resultVal.."</b>"endreturnresultValend-- Return link(s) Commons gallery, or category, or both from wikidata-- Arguments:-- defaultGallery = default gallery link to use, instead of wikidata-- defaultCategory = default category link to use, instead of wikidata-- categoryText = if both gallery and category, text to use in category link ("category" by default)-- bold = whether to make first link bold-- italic = whether to make first link italic-- qid = qid of page to lookup in wikidata (testing only)functionp._getGalleryAndCategory(defaultGallery,defaultCategory,linkText,categoryText,bold,italic,oneSearch,qid)localwp_title,wp_nswp_title,wp_ns,qid=_getTitleQID(qid)categoryText=categoryTextor"category"-- construct default result (which searches for title)localsearchResult=_formatResult("[[Commons:Special:Search/"..wp_title.."|"..(linkTextorwp_title).."]]",bold,italic)ifnotoneSearchthensearchResult=searchResult.." ([[Commons:Special:Search/Category:"..wp_title.."|"..categoryText.."]])"endlocaltrackingCats=""localgalleryLink,galleryConsistentlocalcommonsSitelink=nilifdefaultGallerythengalleryLink=defaultGallerygalleryConsistent=trueelsegalleryLink,galleryConsistent,commonsSitelink=_lookupGallery(qid,true)endlocalgalleryGood=galleryLinkandgalleryConsistentifnotgalleryConsistentandwp_ns==""thentrackingCats="[[Category:Inconsistent wikidata for Commons gallery]]"endlocalcategoryLink,categoryConsistentifdefaultCategorythencategoryLink=defaultCategorycategoryConsistent=trueelsecategoryLink,categoryConsistent=_lookupCategory(qid,defaultGallery,commonsSitelink)endlocalcategoryGood=categoryLinkandcategoryConsistentifnotcategoryConsistentandwp_ns==""thentrackingCats=trackingCats.."[[Category:Inconsistent wikidata for Commons category]]"endlocalfirstLinkifgalleryGoodthenfirstLink=galleryLinklinkText=linkTextorgalleryLinkelseifcategoryGoodthenfirstLink="Category:"..categoryLinklinkText=linkTextorcategoryLinkelsereturnsearchResult..trackingCatsendlocalresultVal=_formatResult("[[Commons:"..firstLink.."|"..linkText.."]]",bold,italic)ifgalleryGoodandcategoryGoodthenresultVal=resultVal.." ([[Commons:Category:"..categoryLink.."|"..categoryText.."]])"endreturnresultVal..trackingCatsend-- Compare two titles with their namespaces strippedlocalfunctiontitleMatch(s1,s2)s1=s1or""s2=s2or""s1=mw.ustring.gsub(s1,"^[^:]+:","")s2=mw.ustring.gsub(s2,"^[^:]+:","")returns1==s2end-- Figure out tracking categories and editor warnings-- Arguments:-- default = Commons link argument passed to template-- fetchGallery = whether to fetch a gallery from Wikidata-- fetchCategory = whether to fetch a category from Wikidata-- qid = force a qid for testing-- Returns:-- tracking category and possible user warning---- Note: the logic for the tracking is quite different than the logic-- for generating Commons links (above). Thus, it is separated into another-- function for code clarity and maintainability. This should not seriously -- affect performance: server time is dominated by fetching wikidata entities,-- and those entities should be cached and shared between the Commons generating-- code and this tracking code.functionp._tracking(default,fetchGallery,fetchCategory,qid)localtitle,wp_ns,wp_qid=_getTitleQID(qid,true)ifwp_ns~=""thentitle=wp_ns..":"..titleend-- only track if test or namespace=article or namespace=categoryifnot(qidorwp_ns==""orwp_ns=="Category")thenreturn""end-- construct warning messagelocalmsg="Commons link does not match Wikidata"msg=msg.."– [[Template:Commons_category#Resolving_discrepancies|please check]]"localprefix="[[Category:Commons "ifnotfetchGalleryandfetchCategorythenprefix=prefix.."category "endprefix=prefix.."link "-- determine title and namespace of wikidata and wp articlelocalwikidata=nil-- Tracking code works for all 4 cases of states of fetchGallery/Category-- fetchGallery takes precedenceiffetchGallerythenwikidata=p._hasGallery(qid)endifwikidata==nilandfetchCategorythenwikidata=p._hasCategory(qid,true)endlocalwp_cat=(wp_ns=="Category")ifdefaultthenifdefault==wikidatathenreturnprefix.."is on Wikidata]]"endiftitleMatch(default,title)thenreturnprefix.."is defined as the pagename]]"..warning(msg)endreturnprefix.."is locally defined]]"..warning(msg)endifwikidatathenreturnprefix.."from Wikidata]]"endreturnprefix.."is the pagename]]"end-- Testing-only entry point for _getTitleQIDfunctionp.getTitleQID(frame)localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false})localtext,ns,qid=_getTitleQID(args[1],args[2])returntext..","..ns..","..(qidor"nil")end-- Testing-only entry point for _lookupFallbackfunctionp.lookupFallback(frame)localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false})localfallback=_lookupFallback(args[1],args[2])returnfallbackor"nil"end-- Find the Commons gallery page associated with articlefunctionp.getGallery(frame)localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false})returnp._getCommons("",args[1],args.linktext,args.search,args.fallback,args.lcfirst,args.qid)end-- Find the Commons category page associated with articlefunctionp.getCategory(frame)localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false})localretval=p._getCommons("Category",args[1],args.linktext,args.search,args.fallback,args.lcfirst,args.qid)ifargs.trackingthenlocaldefault=nilifargs[1]thendefault="Category:"..args[1]endretval=retval..p._tracking(default,false,true,args.qid)endreturnretvalendfunctionp.getGalleryOrCategory(frame)localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false})localretval=p._getGalleryOrCategory(args[1],args.linktext,args.search,args.fallback,args.qid)ifargs.trackingthenretval=retval..p._tracking(args[1],true,true,args.qid)endreturnretvalendfunctionp.hasGallery(frame)localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false})returnp._hasGallery(args.qid)or""endfunctionp.hasCategory(frame)localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false})returnp._hasCategory(args.qid)or""endfunctionp.hasGalleryOrCategory(frame)localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false})returnp._hasGallery(args.qid)orp._hasCategory(args.qid)or""endfunctionp.getGalleryAndCategory(frame)localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false})returnp._getGalleryAndCategory(args[1],args[2],args.linktext,args.categoryText,args.bold,args.italic,args.oneSearch,args.qid)endfunctionp.tracking(frame)localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false})returnp._tracking(args[1],args.fetchGallery,args.fetchCategory,args.qid)endreturnp
close