Jump to content
Wikipedia The Free Encyclopedia

Module:Module sandbox/sandbox

From Wikipedia, the free encyclopedia
This is the module sandbox page for Module:Module sandbox (diff).
Module documentation[view] [edit] [history] [purge]


Usage

{{#invoke:Module sandbox|function_name}}

Example

{{#invoke:Module sandbox|main}} yields:

Hello world!

Documentation

Package items

sandbox.hello_world(name) (function)
Prints hello world
Parameter: name Person to address (string)
Returns: hello world string
TODO: make it say "Hello, [name]".
sandbox.main(frame) (function)
Main entrypoint.
Parameter: frame calling frame (table)
Returns: output wikitext
The above documentation is transcluded from Module:Module sandbox/doc. (edit | history)
Editors can experiment in this module's sandbox (edit | diff) and testcases (create) pages.
Add categories to the /doc subpage. Subpages of this module.
 -- Note: Originally written on English Wikipedia as [[w:en:Module:Attached_KML]]
 -- ##### Localisation (L10n) settings #####
 localL10n={
 -- Template parameter names
 -- (replace values in quotes with local parameter names)
 para={
 display="display",
 from="from",
 header="header",
 title="title",
 wikidata="wikidata",
 demo="demo",
 },
 -- Other configuration settings
 config={
 -- controls the format used for inline display, can be set to "box" (default) or "line"
 -- "box" example: https://en.wikipedia.org/wiki/Template:Attached_KML
 -- "line" example: https://sv.wikipedia.org/wiki/Mall:KML
 inline_format="box",
 },
 -- Other strings
 str={
 inline="inline",-- used with display parameter: (|display=inline) or (|display=title) or (|display=inline,title) or (|display=title,inline)
 title="title",-- (as above)
 dsep=",",-- separator between inline and title (comma in the example above)
 kml_prefix="Template:Attached KML/",-- local KML files are stored as subpages of this location
 default_title="Route map",-- default title for links at top of page, when title parameter not used in transclusion
 default_header="",-- default header for links in inline box, when header parameter not used in transclusion
 kml_file="KML file",-- text to display for link to raw KML file
 edit="edit",-- text to display for link to edit KML file
 help="help",-- text to display for help page link
 help_location="Help:Attached KML",-- page to link to for help page link
 err_prepend="Attached KML",-- text to prepend to the error messages, when shown at top of page (display=title)
 cat={-- tracking categories: full wikimarkup required, or set to the empty string ("") to not to track the condition
 wikidata_kml="[[Category:Articles using KML from Wikidata]]",-- tracks mainspace articles using KML from Wikidata
 local_kml="[[Category:Articles using KML not from Wikidata]]",-- tracks mainspace articles not using KML from Wikidata
 error_mqid="[[Category:Attached KML errors|M]]",-- tracks malformed_qid error
 error_badqid="[[Category:Attached KML errors|W]]",-- tracks bad_qid error
 error_noitem="[[Category:Attached KML errors|N]]",-- tracks no_item error
 error_from="[[Category:Attached KML errors|F]]",-- tracks bad_from error
 error_nokml="[[Category:Attached KML errors|K]]",-- tracks no_kml error
 },
 line={-- these strings are only needed if using 'inline_format = "line"' configuration
 start="",-- wikitext to display at start of line, may include image markup, should start with a space
 separator="",-- text to display between links to external mapping providers, should include spaces
 },
 }
 }

 L10n.str.err={-- error messages
 malformed_qid="Error: malformed item id in <code><nowiki>|"..L10n.para.wikidata.."=</nowiki></code>",-- item id doesn't match pattern (number with Q prefix)
 bad_qid="Error: item specified on Wikidata, or in <code><nowiki>|"..L10n.para.wikidata.."=</nowiki></code>, is not a KML file <small>(P31→Q26267864 not found)</small>",-- item doesn't have a P31→Q26267864 statement
 no_item="Error: item specified in <code><nowiki>|"..L10n.para.wikidata.."=</nowiki></code> not found on Wikidata",-- item not found on wikidata
 bad_from="Error: KML file not found, check <code><nowiki>|"..L10n.para.from.."=</nowiki></code>",-- KML specified by from parameter doesn't exist
 no_kml="Error: KML file not found",-- no KML file found
 }

 -- Masks for external mapping providers, in the form:
 -- externalLinkMasks[index-number] = { short = "short-label", long = "long-label", link = "url" }'
 -- The short label is used for the title links; the long label is used for the inline links
 -- Links in the output will be ordered by index-number
 -- Instead of kml file's raw url or encoded raw url, use __KML_URL__ or __KML_URL_E__
 localexternalLinks={}
 externalLinks[1]={
 short="Bing",
 long="Display on Bing Maps",
 link="http://www.bing.com/maps/?mapurl=__KML_URL__"
 }

 -- #### End of L10n settings ####

 -- Table of available wikis, in the order that they are to be searched for kml files
 -- (once a kml file is found, further sites are not checked)
 localsites={
 {
 mw.ustring.match(mw.site.server,"%w+")..mw.ustring.gsub(mw.ustring.lower(mw.site.siteName),"[mp]edia",""),
 mw.ustring.sub(mw.site.server,3),
 ""
 },-- local wiki (listed first so local files can override files on other wikis)
 {"commonswiki","commons.wikimedia.org","c:"},-- Commons would be a logical central repository for KML files (but has no files as of August 2016)
 {"enwiki","en.wikipedia.org","w:en:"},-- largest source of KML files (as of August 2016)
 {"bnwiki","bn.wikipedia.org","w:bn:"},-- other sites with a KML template, listed in alphabetical order
 {"cswiki","cs.wikipedia.org","w:cs:"},
 {"fawiki","fa.wikipedia.org","w:fa:"},
 {"frwiki","fr.wikipedia.org","w:fr:"},
 {"jawiki","ja.wikipedia.org","w:ja:"},
 {"mlwiki","ml.wikipedia.org","w:ml:"},
 {"svwiki","sv.wikipedia.org","w:sv:"},
 {"zhwiki","zh.wikipedia.org","w:zh:"},
 }

 localp,q={},{}

 localfunctionsetCleanArgs(argsTable)
 localcleanArgs={}
 forkey,valinpairs(argsTable)do
 iftype(val)=='string'then
 val=val:match('^%s*(.-)%s*$')
 ifval~=''then
 cleanArgs[key]=val
 end
 else
 cleanArgs[key]=val
 end
 end
 returncleanArgs
 end

 localfunctionsafeReplace(string,pattern,replacement)
 -- avoids "Lua error: invalid capture index" that occurs with string.gsub when the replacement contains one or more literal % character
 localnonpattern_parts=mw.text.split(string,pattern)
 returntable.concat(nonpattern_parts,replacement)
 end

 localfunctionmakeTitleWikitext(titletext,err)
 iferrandL10n.str.err_prependthen
 err=mw.ustring.gsub(err,">",">"..L10n.str.err_prepend.." ",1)
 end

 localtitleLinks={}
 fori,vinipairs(externalLinks)do
 titleLinks[i]=mw.ustring.format("[%s %s]",v.link,v.short)
 end
 returnmw.getCurrentFrame():extensionTag{
 name='indicator',
 args={name='attached-kml'},
 content=mw.ustring.format(
 "<span id=\"coordinates\">\'\'\'%s\'\'\': %s</span>",
 titletext,
 errortable.concat(titleLinks," / ")
 )
 }
 end

 localfunctionmakeInlineWikitext(headertext,url,err)
 localinlineLinks={}
 fori,vinipairs(externalLinks)do
 inlineLinks[i]=mw.ustring.format("[%s %s]",v.link,v.long)
 end
 localeditUrl=mw.ustring.gsub(url,"action=raw","action=edit")
 localwiki_link_class
 ifmw.ustring.find(editUrl,mw.site.server,1,true)then
 wiki_link_class="plainlinks"
 else
 wiki_link_class=""
 end

 ifL10n.config.inline_format=="line"then
 returnmw.ustring.format(
 "<li>%s%s%s (<span class=\"%s\">[%s %s] <span style=\"font-size:85%%;\">([%s %s] • [[%s|%s]])</span></span>)</li>",
 headertext,L10n.str.line.start,
 errortable.concat(inlineLinks,L10n.str.line.separator),
 wiki_link_class,url,L10n.str.kml_file,editUrl,L10n.str.edit,
 L10n.str.help_location,L10n.str.help
 )
 end

 localtext=mw.ustring.format(
 '%s<span class="%s">\'\'\'[%s %s]\'\'\' ([%s %s] • [[%s|%s]])</span>',
 headertext,wiki_link_class,url,L10n.str.kml_file,editUrl,
 L10n.str.edit,L10n.str.help_location,L10n.str.help
 )

 iferror#inlineLinks>0then
 text=mw.ustring.format(
 "%s<ul><li>%s</li></ul>",
 text,
 errortable.concat(inlineLinks,"</li><li>")
 )
 end

 returnrequire('Module:Side box')._main({
 class='attached-kml',
 text=text
 })
 end

 localfunctionmakeKmldataDiv(link,s_index)
 returnmw.ustring.format(
 '<div class="kmldata" data-server="%s" title="%s">[[%s%s]]</div>',
 sites[s_index][2],link,sites[s_index][3],link
 )
 end

 localfunctionmakeError(msg,cat)
 returnmw.ustring.format(
 '<strong class="attached-kml-error">%s</strong>%s',
 msg,
 mw.title.getCurrentTitle():inNamespaces(0,118)andcator''
 )
 end

 localfunctiongetUrlFromQid(kml_qid)
 localpcall_result,kml_entity=pcall(mw.wikibase.getEntity,kml_qid)
 ifnotpcall_resultthenreturnnil,nil,nil,makeError(L10n.str.err.no_item,L10n.str.cat.error_noitem)end-- Error if entity doesn't exist

 localp31_claim=kml_entity:getBestStatements("P31")-- P31 is property "instance of"
 localhas_good_p31
 fork,vinpairs(p31_claim)do
 if(p31_claim[k]andp31_claim[k].mainsnak.snaktype=="value"and
 p31_claim[k].mainsnak.datavalue.type=="wikibase-entityid"and
 p31_claim[k].mainsnak.datavalue.value["numeric-id"]==26267864)then
 has_good_p31=true
 end
 end
 ifnot(has_good_p31)then-- Error if item isn't a kml file
 returnnil,nil,nil,makeError(L10n.str.err.bad_qid,L10n.str.cat.error_badqid)
 end

 localkml_sitelink
 localkml_siteindex
 localkml_url
 fori,vinipairs(sites)do
 kml_sitelink=kml_entity:getSitelink(v[1])
 ifkml_sitelinkthen
 kml_url="https://"..v[2].."/w/index.php?title="..mw.uri.encode(kml_sitelink,"WIKI").."&action=raw"
 kml_siteindex=i
 end
 ifkml_urlthenbreakend
 end
 returnkml_urlornil,kml_sitelinkornil,kml_siteindexornil,nil
 end

 -- Attempts to get url from linked wikidata items, will return nil if it can't
 localfunctiongetUrlFromWikidata()
 localentity=mw.wikibase.getEntityObject()
 ifnotentitythenreturnnilend

 localkml_claim=entity:getBestStatements("P3096")-- P3096 is property "KML file"

 ifkml_claimthen
 -- get the QID of the first value of the property
 if(kml_claim[1]andkml_claim[1].mainsnak.snaktype=="value"andkml_claim[1].mainsnak.datavalue.type=="wikibase-entityid")then
 localkml_qid="Q"..kml_claim[1].mainsnak.datavalue.value["numeric-id"]
 returngetUrlFromQid(kml_qid)
 else
 returnnil-- TODO: error message
 end
 else
 returnnil-- TODO: error message
 end
 end

 functionp.main(frame)
 localparent=frame
 localArgs=setCleanArgs(frame.args)

 localqid=Args[L10n.para.wikidata]ornil

 -- get KML file url
 localwikiUrl,wikiTitle,wikiLink,trackingWikitext,kmlError
 ifnot(Args[L10n.para.from])then
 ifnotqidthen
 wikiUrl,wikiLink,siteindex,kmlError=getUrlFromWikidata()
 elseifmw.ustring.find(qid,"^Q%d+")then
 wikiUrl,wikiLink,siteindex,kmlError=getUrlFromQid(qid)
 else
 kmlError=makeError(L10n.str.err.malformed_qid,L10n.str.cat.error_mqid)
 end
 end

 ifnot(wikiUrl)then
 -- FIXME? this smells bad. shouldn't need to make a new title of a to_string
 -- from the current title and then turn it into text form
 wikiLink=Args[L10n.para.from]ormw.title.new(tostring(mw.title.getCurrentTitle())).text
 wikiLink=L10n.str.kml_prefix..wikiLink
 wikiTitle=mw.title.new(wikiLink)

 ifnot(wikiTitle.exists)andnot(kmlError)then
 ifArgs[L10n.para.from]then
 kmlError=makeError(L10n.str.err.bad_from,L10n.str.cat.error_from)
 else
 kmlError=makeError(L10n.str.err.no_kml,L10n.str.cat.error_nokml)
 end
 end
 wikiUrl=wikiTitle:fullUrl("action=raw","https")
 siteindex=1
 trackingWikitext=mw.ustring.format(
 '<div title="KML & Wikidata" class="attached-kml-wikidata">KML is not from Wikidata</div>%s',
 mw.title.getCurrentTitle():inNamespace(0)andL10n.str.cat.local_kmlor''
 )
 else
 trackingWikitext=mw.ustring.format(
 '<div title="KML & Wikidata" class="attached-kml-wikidata">KML is from Wikidata</div>%s',
 mw.title.getCurrentTitle():inNamespace(0)andL10n.str.cat.wikidata_kmlor''
 )
 end

 wikiTitle=mw.title.new(wikiLink)
 ifwikiTitle.existsthen
 localtransclusion=wikiTitle:getContent()-- hack to register the template as transcluded.
 end

 -- replace __KML_URL__ or __KML_URL_E__ with actual values
 localencodedWikiUrl=mw.uri.encode(wikiUrl,"PATH")
 fori,vinipairs(externalLinks)do
 localel1=safeReplace(v.link,"__KML_URL__",wikiUrl)
 localel2=safeReplace(el1,"__KML_URL_E__",encodedWikiUrl)
 externalLinks[i]["link"]=el2
 end

 -- suppress errors and categories if demo parameter is set
 ifArgs[L10n.para.demo]then
 kmlError=nil
 trackingWikitext=""
 end

 localwikitext=""
 ifArgs[L10n.para.display]then
 localdisplay=mw.text.split(Args[L10n.para.display],'%s*'..L10n.str.dsep..'%s*')
 ifdisplay[1]==L10n.str.titleordisplay[2]==L10n.str.titlethen
 wikitext=makeTitleWikitext(Args[L10n.para.title]orL10n.str.default_title,kmlError)
 end
 ifdisplay[1]==L10n.str.inlineordisplay[2]==L10n.str.inlineor(display[1]~=L10n.str.titleanddisplay[2]~=L10n.str.title)then
 localinlineWikitext=makeInlineWikitext(Args[L10n.para.header]orL10n.str.default_header,wikiUrl,kmlError)
 wikitext=wikitext..inlineWikitext
 end
 else
 wikitext=makeInlineWikitext(Args[L10n.para.header]orL10n.str.default_header,wikiUrl,kmlError)
 end
 wikitext=wikitext..makeKmldataDiv(wikiLink,siteindex)..trackingWikitext

 returnframe:extensionTag{
 name='templatestyles',args={src='Module:Attached KML/styles.css'}
 }..frame:preprocess(wikitext)

 end

 functionq.main(frame)
 localentity=mw.wikibase.getEntity(frame.args.Q)
 localentity=mw.wikibase.getEntity()

 localkml=entity:getBestStatements("P3096")

 ifentity==nilthen
 returnframe:preprocess("Hello".."Bye")
 else
 returnframe:preprocess("Hello"..tostring(kml[1]).."Bye")
 end
 end

 returnq

AltStyle によって変換されたページ (->オリジナル) /