Module:Commons link
- Afrikaans
- العربية
- Արեւմտահայերէն
- تۆرکجه
- Basa Bali
- বাংলা
- Banjar
- Беларуская
- भोजपुरी
- Bikol Central
- Cebuano
- Dansk
- Ελληνικά
- فارسی
- ગુજરાતી
- गोंयची कोंकणी / Gõychi Konknni
- 한국어
- Hausa
- Hrvatski
- Ilokano
- Bahasa Indonesia
- Íslenska
- Kurdî
- Lietuvių
- Madhurâ
- Македонски
- മലയാളം
- मराठी
- Bahasa Melayu
- ꯃꯤꯇꯩ ꯂꯣꯟ
- မြန်မာဘာသာ
- नेपाली
- 日本語
- Oʻzbekcha / ўзбекча
- ਪੰਜਾਬੀ
- ပအိုဝ်ႏဘာႏသာႏ
- සිංහල
- Simple English
- Slovenščina
- کوردی
- Suomi
- တႆး
- ไทย
- Türkçe
- Türkmençe
- اردو
- Tiếng Việt
- 文言
- 中文
- Bajau Sama
- Betawi
See the protection policy and protection log for more details. Please discuss any changes on the talk page; you may submit an edit request to ask an administrator to make an edit if it is uncontroversial or supported by consensus. You may also request that this page be unprotected.
To avoid major disruption and server load, any changes should be tested in the module's /sandbox or /testcases subpages, or in your own module sandbox. The tested changes can be added to this page in a single edit. Consider discussing changes on the talk page before implementing them.
For testing the sandbox, see Module:Commons link/sandbox/testcases.
Usage
{{#invoke:Commons link|getGallery}}
- Use wikidata to find Commons gallery corresponding to this article. If unable to find gallery in wikidata, default to searching for PAGENAME in Commons.
{{#invoke:Commons link|getGallery|title|linktext=text}}
- Link to Commons gallery at
title. Optionally, usetextas displayed link text.
{{#invoke:Commons link|getGallery|search=string|linktext=text}}
- Link to Commons search for
string. Optionally, usetextas displayed link text.
{{#invoke:Commons link|getCategory|fallback=string|linktext=text}}
- Use wikidata first, then if failure, use Commons search for
string. Optionally, usetextas displayed link text.
{{#invoke:Commons link|getCategory}}
- Use wikidata to find Commons category corresponding to this article. If unable to find category in wikidata, default to searching for Category:PAGENAME in Commons.
{{#invoke:Commons link|getCategory|title|linktext=text}}
- Link to Commons category at
Category:title. Optionally, usetextas displayed link text.
{{#invoke:Commons link|getCategory|search=string|linktext=text}}
- Link to Commons search for
Category:string. Optionally, usetextas displayed link text.
{{#invoke:Commons link|getCategory|fallback=string|linktext=text}}
- Use wikidata first, then if failure, use Commons search for
Category:string. Optionally, usetextas displayed link text.
{{#invoke:Commons link|getGalleryOrCategory}}
- Use wikidata to find "best" single Commons link: try gallery first, fall back to category. Other arguments as above.
{{#invoke:Commons link|getGalleryAndCategory}}
- Lua to implement {{commons and category }}: return Commons gallery, Commons category, or both (if both found)
{{#invoke:Commons link|getGalleryAndCategory|GalleryName|CategoryName}}
- Either GalleryName or CategoryName or both can be supplied, will override wikidata search
{{#invoke:Commons link|bold=1|italic=1|nowrap=1|lcfirst=1}}
- Format of first link can be specified (any combination of bold, italic, nowrap, and lower-case first character)
{{#invoke:Commons link|linktext=link|categoryText=category}}
- Text in the first link, and the second (category) link can be overridden, also.
{{#invoke:Commons link|tracking=1}}
- Module can generate tracking categories for mismatch between supplied arguments and Wikidata.
Editors can experiment in this module's sandbox (edit | diff) and testcases (edit | run) pages.
Subpages of this module.
require('strict') -- Module to find commons galleries and categories based on wikidata entries localgetArgs=require('Module:Arguments').getArgs localp={} -- 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+$") end localfunction_lcfirst(s) returnmw.ustring.lower(mw.ustring.sub(s,1,1))..mw.ustring.sub(s,2) end -- Format displayed linktext -- Arguments: -- s = string to display -- formatting = formatting table: -- formatting.linktext = if defined, override s -- formatting.lcfirst = lower case the first letter in display -- formatting.bold = whether to bold the display -- formatting.italic = whether to italicize the display -- formatting.nowrap = set nowrapping -- Returns: -- formatted string localfunction_formatResult(s,formatting) localresultVal=formatting.linktextors ifformatting.lcfirstthen resultVal=_lcfirst(resultVal) end localstyle="" ifformatting.italicthenstyle="font-style:italic; "end ifformatting.boldthenstyle=style.."font-weight:bold; "end ifformatting.nowrapthenstyle=style.."white-space:nowrap; "end ifstyle~=""then resultVal='<span style="'..mw.text.trim(style)..'">'..resultVal..'</span>' end returnresultVal end -- 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=string.gsub(titleObject.nsText,"_"," ")-- [[phab:T369784]] ifnot_validQID(qid)then qid=mw.wikibase.getEntityIdForCurrentPage() returntitleObject.text,nsText,qid end -- 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 sitelink localfirstColon=mw.ustring.find(title,':',1,true) localqidNsText="" iffirstColonthen qidNsText=mw.ustring.sub(title,1,firstColon-1) title=mw.ustring.sub(title,firstColon+1) end ifnsQidthen returntitle,qidNsText,qid end returntitle,nsText,qid end -- 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 article localfunction_lookupGallery(qid,fetch,commonsSitelink) ifnot_validQID(qid)then returnnil,true,nil end qid=qid:upper() localgalleryLink=nil localconsistent=true -- look up commons sitelink for article, use if not category iffetchthen commonsSitelink=mw.wikibase.getSitelink(qid,"commonswiki")orcommonsSitelink end ifcommonsSitelinkandmw.ustring.sub(commonsSitelink,1,9)~="Category:"then galleryLink=commonsSitelink end -- P935 is the "commons gallery" property for this article localP935=mw.wikibase.getBestStatements(qid,"P935")[1] ifP935andP935.mainsnak.datavaluethen localgallery=P935.mainsnak.datavalue.value ifgalleryLinkandgalleryLink~=gallerythen consistent=false else galleryLink=gallery end end returngalleryLink,consistent,commonsSitelink end -- 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 nil localfunction_lookupFallback(qid,property) ifnot_validQID(qid)ornot_validProp(property)then returnnil end qid=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 article localsitelink=mw.wikibase.getSitelink(value.mainsnak.datavalue.value.id,"commonswiki") -- Check to see if it starts with "Category:". If so, strip it and return ifsitelinkandmw.ustring.sub(sitelink,1,9)=="Category:"then returnmw.ustring.sub(sitelink,10) end end returnnil end -- 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 article localfunction_lookupCategory(qid,fetch,commonsSitelink) ifnot_validQID(qid)then returnnil,true,nil end qid=qid:upper() localcategoryLink=nil localconsistent=true -- look up commons sitelink for article, use if starts with "Category:" iffetchthen commonsSitelink=mw.wikibase.getSitelink(qid,"commonswiki")orcommonsSitelink end ifcommonsSitelinkandmw.ustring.sub(commonsSitelink,1,9)=="Category:"then categoryLink=mw.ustring.sub(commonsSitelink,10) end -- P910 is the "topic's main category". Look for commons sitelink there localfallback=_lookupFallback(qid,"P910") iffallbackthen ifcategoryLinkandcategoryLink~=fallbackthen consistent=false qid=nil else categoryLink=fallback end end -- P1754 is the "list's main category". Look for commons sitelink there fallback=_lookupFallback(qid,"P1754") iffallbackthen ifcategoryLinkandcategoryLink~=fallbackthen consistent=false qid=nil else categoryLink=fallback end end -- P373 is the "commons category" property for this article. This is -- a low-quality field, so should only be used as a last resort. ifcategoryLink==niland_validQID(qid)then localP373=mw.wikibase.getBestStatements(qid,"P373")[1] ifP373andP373.mainsnak.datavaluethen categoryLink=P373.mainsnak.datavalue.value consistent=true-- P373 is never used if anything else is available end end returncategoryLink,consistent,commonsSitelink end -- Does the article have a Commons gallery, and is it consistent? -- Arguments: -- qid = QID to lookup in wikidata (for testing only) -- Returns: -- filename at Commons, bool: is wikidata consistent for this article? functionp._hasGalleryConsistent(qid) localwp_title,wp_ns wp_title,wp_ns,qid=_getTitleQID(qid) return_lookupGallery(qid,true) end -- Does the article have a corresponding Commons gallery? -- Arguments: -- qid = QID to lookup in wikidata (for testing only) -- Returns: -- filename at Commons if so, false if not functionp._hasGallery(qid) localgalleryLink,consistent=p._hasGalleryConsistent(qid) returnconsistentandgalleryLink end -- Does the article have a Commons category? Is wikidata consistent for that? -- Arguments: -- qid = QID to lookup in wikidata (for testing only) -- prefix = whether to add "Category:" to return string (default true) -- Returns: -- filename at Commons, bool: consistent functionp._hasCategoryConsistent(qid,prefix) ifprefix==nilthen prefix=true end localwp_title,wp_ns wp_title,wp_ns,qid=_getTitleQID(qid) localcategoryLink,consistent=_lookupCategory(qid,true) ifcategoryLinkandprefixthen categoryLink="Category:"..categoryLink end returncategoryLink,consistent end -- 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 not functionp._hasCategory(qid,prefix) localcategoryLink,consistent=p._hasCategoryConsistent(qid,prefix) returnconsistentandcategoryLink end -- Create Commons link corresponding to current article -- Arguments: -- namespace = namespace in Commons ("" for galleries) -- default = use as Commons link, don't access wikidata -- search = string to search for -- fallback = string to search for if wikidata fails -- formatting = formatting parameters -- qid = QID to lookup in wikidata (for testing only) -- Returns: -- formatted wikilink to Commons in specified namespace functionp._getCommons(namespace,default,search,fallback,formatting,qid) localnsColon ifnotnamespaceornamespace==""then nsColon="" else nsColon=namespace..":" end ifdefaultthen return"[[Commons:"..nsColon..default.."|".._formatResult(default,formatting).."]]" end ifsearchthen return"[[Commons:Special:Search/"..nsColon..search.."|".._formatResult(search,formatting).."]]" end localwp_title,wp_ns wp_title,wp_ns,qid=_getTitleQID(qid) localcommonsLink=nil localconsistent=true ifnsColon==""then commonsLink,consistent=_lookupGallery(qid,true) elseifnamespace:lower()=="category"then commonsLink,consistent=_lookupCategory(qid,true) end -- use wikidata if consistent ifcommonsLinkandconsistentthen return"[[Commons:"..nsColon..commonsLink.."|".._formatResult(commonsLink,formatting).."]]" end -- if not consistent, fall back to search and add to tracking cat -- construct default result (which searches for title) localsearchResult="[[Commons:Special:Search/"..nsColon..(fallbackorwp_title) .."|".._formatResult(fallbackorwp_title,formatting).."]]" ifnotconsistentandwp_ns==""then localfriendlyNS ifnsColon==""then friendlyNS="gallery" else friendlyNS=namespace:lower() end searchResult=searchResult.."[[Category:Inconsistent wikidata for Commons "..friendlyNS.."]]" end returnsearchResult end -- Returns "best" Commons link: first look for gallery, then try category -- Arguments: -- default = use as Commons link, don't access wikidata -- search = string to search for -- fallback = string to search for if wikidata lookup fails -- formatting = formatting parameters -- qid = QID to lookup in wikidata (for testing only) -- Returns: -- formatted wikilink to Commons "best" landing page functionp._getGalleryOrCategory(default,search,fallback,formatting,qid) ifdefaultthen return"[[Commons:"..default.."|".._formatResult(default,formatting).."]]" end ifsearchthen return"[[Commons:Special:Search/"..search.."|".._formatResult(search,formatting).."]]" end localwp_title,wp_ns wp_title,wp_ns,qid=_getTitleQID(qid) localtrackingCats="" localgalleryLink,consistent,commonsSitelink=_lookupGallery(qid,true) -- use wikidata if either sitelink or P935 exist, and they both agree ifgalleryLinkandconsistentthen return"[[Commons:"..galleryLink.."|".._formatResult(galleryLink,formatting).."]]" end ifnotconsistentandwp_ns==""then trackingCats="[[Category:Inconsistent wikidata for Commons gallery]]" end -- if gallery is not good, fall back looking for category localcategoryLink categoryLink,consistent=_lookupCategory(qid,false,commonsSitelink) ifcategoryLinkandconsistentthen return"[[Commons:Category:"..categoryLink.."|".._formatResult(categoryLink,formatting).."]]"..trackingCats end ifnotconsistentandwp_ns==""then trackingCats=trackingCats.."[[Category:Inconsistent wikidata for Commons category]]" end -- return search result looking for title as last attempt return"[[Commons:Special:Search/"..(fallbackorwp_title).. "|".._formatResult(fallbackorwp_title,formatting).."]]"..trackingCats end -- 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) -- oneSearch = only emit one search result -- formatting = formatting parameters -- qid = qid of page to lookup in wikidata (testing only) functionp._getGalleryAndCategory(defaultGallery,defaultCategory, categoryText,oneSearch,formatting,qid ) localwp_title,wp_ns wp_title,wp_ns,qid=_getTitleQID(qid) categoryText=categoryTextor"category" localtrackingCats="" localgalleryLink,galleryConsistent localcommonsSitelink=nil ifdefaultGallerythen galleryLink=defaultGallery galleryConsistent=true else galleryLink,galleryConsistent,commonsSitelink=_lookupGallery(qid,true) end localgalleryGood=galleryLinkandgalleryConsistent ifnotgalleryConsistentandwp_ns==""then trackingCats="[[Category:Inconsistent wikidata for Commons gallery]]" end localcategoryLink,categoryConsistent ifdefaultCategorythen categoryLink=defaultCategory categoryConsistent=true else categoryLink,categoryConsistent=_lookupCategory(qid,defaultGallery,commonsSitelink) end localcategoryGood=categoryLinkandcategoryConsistent ifnotcategoryConsistentandwp_ns==""then trackingCats=trackingCats.."[[Category:Inconsistent wikidata for Commons category]]" end localfirstLink -- construct default result (which searches for title) localsearchResult="[[Commons:Special:Search/"..wp_title.."|".._formatResult(wp_title,formatting).."]]" ifnotoneSearchthen searchResult=searchResult.." ([[Commons:Special:Search/Category:"..wp_title.."|"..categoryText.."]])" end locallinkText=nil ifgalleryGoodthen firstLink=galleryLink linkText=galleryLink elseifcategoryGoodthen firstLink="Category:"..categoryLink linkText=categoryLink else returnsearchResult..trackingCats end localresultVal="[[Commons:"..firstLink.."|".._formatResult(linkText,formatting).."]]" ifgalleryGoodandcategoryGoodthen resultVal=resultVal.." ([[Commons:Category:"..categoryLink.."|"..categoryText.."]])" end returnresultVal..trackingCats end -- Compare two titles with their namespaces stripped localfunctiontitleMatch(s1,s2) s1=s1or"" s2=s2or"" s1=mw.ustring.gsub(s1,"^[^:]+:","") s2=mw.ustring.gsub(s2,"^[^:]+:","") returns1==s2 end localgalleryTrackingCats={ commons_link_on_wikidata='[[Category:Commons link is on Wikidata]]', commons_link_defined_as_pagename='[[Category:Commons link is defined as the pagename]]', commons_link_locally_defined='[[Category:Commons link is locally defined]]', commons_link_from_wikidata='[[Category:Commons link from Wikidata]]', commons_link_is_pagename='[[Category:Commons link is the pagename]]', inconsistent='[[Category:Inconsistent wikidata for Commons gallery]]' } localcategoryTrackingCats={ commons_link_on_wikidata='[[Category:Commons category link is on Wikidata]]', commons_link_defined_as_pagename='[[Category:Commons category link is defined as the pagename]]', commons_link_locally_defined='[[Category:Commons category link is locally defined]]', commons_link_from_wikidata='[[Category:Commons category link from Wikidata]]', commons_link_is_pagename='[[Category:Commons category link is the pagename]]', inconsistent='[[Category:Inconsistent wikidata for Commons category]]' } localfunctionselectTrackingCat(trackingCats,wikidata,consistent,default,title) ifnotconsistentthen returntrackingCats.inconsistent end ifdefaultthen -- construct warning message ifdefault==wikidatathen returntrackingCats.commons_link_on_wikidata end localwarning="" ifwikidatathen localgenerateWarning=require('Module:If preview')._warning warning=generateWarning({ "Commons link does not match Wikidata – [[Template:Commons_category#Resolving_discrepancies|please check]]" }) end iftitleMatch(default,title)then returntrackingCats.commons_link_defined_as_pagename..warning end returntrackingCats.commons_link_locally_defined..warning end ifwikidatathen returntrackingCats.commons_link_from_wikidata end returntrackingCats.commons_link_is_pagename end -- 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~=""then title=wp_ns..":"..title end -- only track if test or namespace=article or namespace=category ifnot(qidorwp_ns==""orwp_ns=="Category")then return"" end -- determine title and namespace of wikidata and wp article localwikidata=nil localconsistent=nil -- Tracking code works for all 4 cases of states of fetchGallery/Category -- fetchGallery takes precedence iffetchGallerythen wikidata,consistent=p._hasGalleryConsistent(qid) ifdefaultornotfetchCategoryor(consistentandwikidata)then returnselectTrackingCat(galleryTrackingCats,wikidata,consistent, default,title) end end iffetchCategorythen localcat_wikidata,cat_consistent=p._hasCategoryConsistent(qid,true) ifnotfetchGalleryor(cat_consistentandcat_wikidata)then returnselectTrackingCat(categoryTrackingCats,cat_wikidata, cat_consistent,default,title) end returnselectTrackingCat(galleryTrackingCats,wikidata,consistent, default,title) end return""-- nothing fetched, nothing tracked end localfunction_createFormatting(args) localformatting={} formatting.linktext=args.linktext localyesNo=require('Module:Yesno') formatting.lcfirst=yesNo(args.lcfirst) formatting.bold=yesNo(args.bold) formatting.italic=yesNo(args.italic) formatting.nowrap=yesNo(args.nowrap) returnformatting end -- Testing-only entry point for _getTitleQID functionp.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 _lookupFallback functionp.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 article functionp.getGallery(frame) localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false}) returnp._getCommons("",args[1],args.search,args.fallback,_createFormatting(args),args.qid) end -- Find the Commons category page associated with article functionp.getCategory(frame) localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false}) localretval=p._getCommons("Category",args[1], args.search,args.fallback,_createFormatting(args),args.qid ) ifargs.trackingthen localdefault=nil ifargs[1]then default="Category:"..args[1] end retval=retval..p._tracking(default,false,true,args.qid) end returnretval end functionp.getGalleryOrCategory(frame) localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false}) localretval=p._getGalleryOrCategory( args[1],args.search,args.fallback,_createFormatting(args),args.qid ) ifargs.trackingthen retval=retval..p._tracking(args[1],true,true,args.qid) end returnretval end functionp.hasGallery(frame) localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false}) returnp._hasGallery(args.qid)or"" end functionp.hasCategory(frame) localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false}) returnp._hasCategory(args.qid)or"" end functionp.hasGalleryOrCategory(frame) localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false}) returnp._hasGallery(args.qid)orp._hasCategory(args.qid)or"" end functionp.getGalleryAndCategory(frame) localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false}) returnp._getGalleryAndCategory(args[1],args[2], args.categoryText,args.oneSearch,_createFormatting(args),args.qid) end functionp.tracking(frame) localargs=getArgs(frame,{frameOnly=true,parentOnly=false,parentFirst=false}) returnp._tracking(args[1],args.fetchGallery,args.fetchCategory,args.qid) end returnp