Jump to content

Module:Excerpt slideshow/sandbox

From Wikipedia, the free encyclopedia
localp={}localexcerptModule=require('Module:Excerpt/portals/sandbox')localslideshowModule=require('Module:Random slideshow/sandbox')localrandomModule=require('Module:Random')localDEFAULT_LIMIT=25-- max number of excerpts to be shown in the slideshowlocalSOURCE_PAGES_LIMIT=10-- max number of pages to check for links / list items-- begin BHG addition for tracking source pageslocalsourcepgagesused={};localsourcepgagesusedcounter=0;localarticlelistcount=-1;localusesEmbeddedList=false;-- end BHG addition for tracking source pagesfunctioncleanupArgs(argsTable)localcleanArgs={}forkey,valinpairs(argsTable)doiftype(val)=='string'thenval=val:match('^%s*(.-)%s*$')ifval~=''thencleanArgs[key]=valendelsecleanArgs[key]=valendendreturncleanArgsendfunctionisDeclined(val)ifnotvalthenreturnfalseendlocaldeclinedWords=" decline declined exclude excluded false none not no n off omit omitted remove removed "returnstring.find(declinedWords,' '..val..' ',1,true)andtrueorfalseend--[[ @param {String} wikitext: Wikitext of just the list (i.e. each line is a list item) @param {String} symbol: Special character used in the wikitext markup for the list, e.g. '*' or '#' @param {String} outerTag: Text portion of the tag for each list or sublist, e.g. 'ul' or 'ol' @param {String} innerTag: Text portion of the tag for each list item, e.g. 'li']]localwikitextToHtmlList=function(wikitext,symbol,outerTag,innerTag)locallistParts={}forlevel,iteminmw.ustring.gmatch('\n'..wikitext..'\n','\n(%'..symbol..'+)(.-)%f[\n]')dotable.insert(listParts,{level=level,item=item})endtable.insert(listParts,{level='',item=''})localhtmlList={}fori,thisinipairs(listParts)dolocalisFirstItem=(i==1)localisLastItem=(i==#listParts)locallastLevel=isFirstItemand''orlistParts[i-1]['level']localtagsif#lastLevel==#this.levelthentags='</'..innerTag..'><'..innerTag..'>'elseif#this.level>#lastLevelthentags=string.rep('<'..outerTag..'><'..innerTag..'>',#this.level-#lastLevel)elseifisLastItemthentags=string.rep('</'..innerTag..'></'..outerTag..'>',#lastLevel)else-- ( #this.level < #lastLevel ) and not last itemtags=string.rep('</'..innerTag..'></'..outerTag..'>',#lastLevel-#this.level)..'</'..innerTag..'><'..innerTag..'>'endtable.insert(htmlList,tags..this.item)endreturntable.concat(htmlList)end--[[ @param {String} wikitext: Wikitext excertp containg zero or more lists @param {String} symbol: Special character used in the wikitext markup for the list, e.g. '*' or '#' @param {String} outerTag: Text portion of the tag for each list or sublist, e.g. 'ul' or 'ol' @param {String} innerTag: Text portion of the tag for each list item, e.g. 'li']]localgsubWikitextLists=function(wikitext,symbol,outerTag,innerTag)-- temporarily remove list linebreaks... wikitext=mw.ustring.gsub(wikitext..'\n','\n%'..symbol,'¿¿¿'..symbol)-- ...so we can grab the whole list (and just the list)...returnmw.ustring.gsub(wikitext,'¿¿¿%'..symbol..'[^\n]+',function(listWikitext)-- ...and then reinstate linebreaks...listWikitext=mw.ustring.gsub(listWikitext,'¿¿¿%'..symbol,'\n'..symbol)-- ...and finally do the conversionreturnwikitextToHtmlList(listWikitext,symbol,outerTag,innerTag)end)end--[[ help gsub strip tables and templates that aren't part of the prose, and remove linebreaks from within other templates, and preprocess parser functions ]]localprocessBraces=function(t)localisTable=mw.ustring.sub(mw.text.trim(t),2,2)=='|'ifisTablethenreturn''end-- else it's a template or parser functionlocalfirst=mw.ustring.sub(t,1,1)locallast=mw.ustring.sub(t,-1)localisNotPartOfProse=first=='\n'andlast=='\n'ifisNotPartOfProsethenreturn''endlocalisParserFunction=mw.ustring.sub(mw.text.trim(t),3,3)=='#'ifisParserFunctionthenlocalframe=mw.getCurrentFrame()returnframe:preprocess(t)end-- else remove internal linebreaksreturnmw.ustring.gsub(t,'\n*','')endlocalcleanUpExcerpt=function(excerpt)-- strip galleriesexcerpt=mw.ustring.gsub(excerpt,"<%s*[Gg]allery.->.-<%s*/%s*[Gg]allery%s*>","")-- strip tables and block templates; strip newlinesexcerpt=mw.ustring.gsub(excerpt..'\n','\n?%b{}\n?',processBraces)-- replace wikitext bulleted lists with html bulleted listsexcerpt=gsubWikitextLists(excerpt,'*','ul','li')-- replace wikitext numbered lists with html numbered listsexcerpt=gsubWikitextLists(excerpt,'#','ol','li')excerpt=mw.text.trim(excerpt)returnexcerptendfunctionmakeGalleryArgs(titles,options,limit,nonRandom)localgalleryArgs={}localtitlesSequence={}locali=1whiletitles[i]dotitlesSequence[i]=titles[i]i=i+1endlocalsortedTitles=nonRandomandtitlesSequenceorrandomModule.main('array',{t=titlesSequence,limit=limit})for_i,titleinipairs(sortedTitles)doif(#galleryArgs/2)<limitthenlocalsuccess,excerpt=pcall(excerptModule.get,title,options)ifnotsuccessthenmw.log("require('Module:Excerpt').get failed: "..excerpt)-- probably got a redlinkexcerpt=nilendifexcerptandexcerpt~=''and#excerpt>10then-- check again in case we had a few characters plus (Full article...)excerpt=cleanUpExcerpt(excerpt)ifoptions.morethenexcerpt=excerpt.." ('''[["..title.."|"..options.more.."]]''')"endlocaltext='<div style="text-align:left;">'..mw.ustring.gsub(excerpt,'%c','<br>')..'</div>'table.insert(galleryArgs,'File:Blank.png')table.insert(galleryArgs,text)endendendifnonRandomthengalleryArgs.random='false'endif#galleryArgs==0andoptions.nostubsthen-- try again, this time including stubsoptions.nostubs=falsereturnmakeGalleryArgs(titles,options,limit,nonRandom)elsereturngalleryArgsendendlocalmakeOptions=function(args)localoptions=args-- pick up miscellaneous options: more, errors, fileargsoptions.paraflags=excerptModule.numberFlags(args.paragraphsor"")-- parse paragraphs, e.g. "1,3-5" → {"1","3-5"}options.fileflags=excerptModule.numberFlags(args.filesor"")-- parse file numbersoptions.ignoreOnlyincludes=options.ignoreOnlyincludes==nilandtrueoroptions.ignoreOnlyincludes-- default to trueifargs.nostubsandisDeclined(args.nostubs)thenoptions.nostubs=falseelseoptions.nostubs=trueendreturnoptionsendlocalisArticle=function(pagetitle)localtitleObject=mw.title.new(pagetitle)return(titleObjectandtitleObject.namespace==0)andtrueorfalseendlocalgetLinkedTitles=function(args,method,limit)localpagenames={}localii=1localisNotCategorywhileargs[ii]andii<limitdolocalpageContent=excerptModule.getContent(args[ii])ifpageContentthenlocalpageSection=args["section"..ii]orargs["section"]localsectionOnly=args["sectiononly"..ii]orargs["sectiononly"]localtext=pageContentifpageSectionthen-- check relevant section onlylocalsuccess,result=pcall(excerptModule.getSection,pageContent,pageSection,sectionOnly)ifnotsuccessthenmw.log("require('Module:Excerpt').getSection failed on the content of "..args[ii]..": "..result)result=nilendtext=resultorpageContentend-- begin BHG addition for tracking source pageslocalthisPage=mw.title.getCurrentTitle().nsText..":"..mw.title.getCurrentTitle().textthisPage=thisPage:gsub('_',' ')-- fix the nsText part, until [[phab:T369784]] is resolvedlocalthisBareParam=mw.ustring.gsub(args[ii],"^([^#]+).*$","%1",1)-- strip any section anchor from the parameter's page namethisBareParam=thisBareParam:gsub('_',' ')-- support underscores in parameter's page nameif(thisPage==thisBareParam)thenusesEmbeddedList=true;end-- end BHG addition for tracking source pages-- replace annotated links with real linkstext=mw.ustring.gsub(text,"{{%s*[Aa]nnotated[ _]link%s*|%s*(.-)%s*}}","[[%1]]")ifmethod=="linked"thenforpinmw.ustring.gmatch(text,"%[%[%s*([^%]|\n]*)")doifisArticle(p)thentable.insert(pagenames,p)endendelse-- listitem: first wikilink on a line beginning *, :#, etc. except in "See also" or later sectiontext=mw.ustring.gsub(text,"\n== *See also.*","")forpinmw.ustring.gmatch(text,"\n:*[%*#][^\n]-%[%[%s*([^%]|\n]*)")doifisArticle(p)thentable.insert(pagenames,p)endendend-- begin BHG addition for tracking source pagesif((method=="listitem")or(method=="linked"))thentable.insert(sourcepgagesused,args[ii])sourcepgagesusedcounter=sourcepgagesusedcounter+1end-- end BHG addition for tracking source pagesendii=ii+1end-- begin BHG addition for trackingarticlelistcount=#pagenames-- end BHG addition for trackingreturnpagenamesend-- Template entry points:-- randomExcerpt: Titles specified in template parameters (equivalent to {{Transclude random excerpt}})p.randomExcerpt=function(frame)localparent=frame.getParent(frame)localoutput=p._excerpt(parent.args,'random')returnframe:extensionTag{name='templatestyles',args={src='Module:Random slideshow/sandbox/styles.css'}}..frame:preprocess(output)end-- linkedExcerpt: Titles from links on one or more pages (similar to {{Transclude linked excerpt}})p.linkedExcerpt=function(frame)localparent=frame.getParent(frame)localoutput=p._excerpt(parent.args,'linked')returnframe:extensionTag{name='templatestyles',args={src='Module:Random slideshow/sandbox/styles.css'}}..frame:preprocess(output)end-- listItemExcerpt: Titles from linked list items one one or more pages (similar to {{Transclude list item excerpt}})p.listItemExcerpt=function(frame)localparent=frame.getParent(frame)localoutput=p._excerpt(parent.args,'listitem')returnframe:extensionTag{name='templatestyles',args={src='Module:Random slideshow/sandbox/styles.css'}}..frame:preprocess(output)end-- Module entry point:p._excerpt=function(_args,method)localargs=cleanupArgs(_args)args.more=excerptModule.getMoreLinkText(_args.more)localoptions=makeOptions(args)locallimit=args.limitandtonumber(args.limit)orDEFAULT_LIMITlocaltitlesifmethod=='linked'ormethod=='listitem'thentitles=getLinkedTitles(args,method,SOURCE_PAGES_LIMIT)elsetitles=argsendlocalgalleryArgs=makeGalleryArgs(titles,options,limit,isDeclined(_args.random))returnslideshowModule._main(galleryArgs,false,'excerptSlideshow-container')..checksourcepages()endp._cleanUpExcerpt=cleanUpExcerpt-- begin BHG addition for tracking source pagesfunctionchecksourcepages()-- no tracking unless we are in Portal namespaceif(mw.title.getCurrentTitle().nsText~="Portal")thenreturn""endlocalpagecounter=0;localtemplatecount=0;localoutlinecount=0;localretval="";localusesEponymousArticle=false;localdebugging=false;localthisPageBareName=mw.title.getCurrentTitle().text;ifdebuggingthenretval='<div style="display:block; border:10px solid green; background-color:#efe; padding:1em; margin:1em">\n----\n'retval=retval.."sourcepgagesusedcounter: "..sourcepgagesusedcounter.."\n----\n"retval=retval.."pages used:"endlocalapageforapageinarrayvalues(sourcepgagesused)doifdebuggingthenretval=retval.."\n# [[:"..apage.."]]"retval=retval.." — ".."First 999 = /"..string.sub(apage,1,999).."/"endif(string.find(apage,"^[tT]emplate ?:")==1)thentemplatecount=templatecount+1;endif(string.find(apage,"^[oO]utline +of ")==1)thenoutlinecount=outlinecount+1;endif(apage==thisPageBareName)thenusesEponymousArticle=true;endpagecounter=pagecounter+1endifdebuggingthenretval=retval.."\nTotal pages: "..pagecounterretval=retval.."\ntemplatecount: "..templatecountretval=retval.."</div>"end-- first do a sanity check that both counting methods have produced the same resultif(sourcepgagesusedcounter==pagecounter)then-- if all pages are templates, then populate tracking categoriesif(pagecounter==templatecount)thenif(templatecount==1)thenretval=retval.."[[Category:Automated article-slideshow portals with article list built solely from one template]]"elseif(templatecount==2)thenretval=retval.."[[Category:Automated article-slideshow portals with article list built solely from two templates]]"elseif(templatecount==3)thenretval=retval.."[[Category:Automated article-slideshow portals with article list built solely from three templates]]"elseif(templatecount>3)thenretval=retval.."[[Category:Automated article-slideshow portals with article list built solely from four or more templates]]"endelseif(templatecount>0)thenretval=retval.."[[Category:Automated article-slideshow portals with article list built using one or more templates, and other sources]]"endendif(outlinecount>=1)thenretval=retval.."[[Category:Automated article-slideshow portals with article list built using one or more outline pages]]"endif(articlelistcount<2)thenretval=retval.."[[Category:Automated article-slideshow portals with less than 2 articles in article list]]"elseif(articlelistcount<=5)thenretval=retval.."[[Category:Automated article-slideshow portals with 2–5 articles in article list]]"elseif(articlelistcount<=10)thenretval=retval.."[[Category:Automated article-slideshow portals with 6–10 articles in article list]]"elseif(articlelistcount<=15)thenretval=retval.."[[Category:Automated article-slideshow portals with 11–15 articles in article list]]"elseif(articlelistcount<=20)thenretval=retval.."[[Category:Automated article-slideshow portals with 16–20 articles in article list]]"elseif(articlelistcount<=25)thenretval=retval.."[[Category:Automated article-slideshow portals with 21–25 articles in article list]]"elseif(articlelistcount<=30)thenretval=retval.."[[Category:Automated article-slideshow portals with 26–30 articles in article list]]"elseif(articlelistcount<=40)thenretval=retval.."[[Category:Automated article-slideshow portals with 31–40 articles in article list]]"elseif(articlelistcount<=50)thenretval=retval.."[[Category:Automated article-slideshow portals with 41–50 articles in article list]]"elseif(articlelistcount<=100)thenretval=retval.."[[Category:Automated article-slideshow portals with 51–100 articles in article list]]"elseif(articlelistcount<=200)thenretval=retval.."[[Category:Automated article-slideshow portals with 101–200 articles in article list]]"elseif(articlelistcount<=500)thenretval=retval.."[[Category:Automated article-slideshow portals with 201–500 articles in article list]]"elseif(articlelistcount<=1000)thenretval=retval.."[[Category:Automated article-slideshow portals with 501–1000 articles in article list]]"elseif(articlelistcount>1000)thenretval=retval.."[[Category:Automated article-slideshow portals with over 1000 articles in article list]]"endifusesEmbeddedListthenretval=retval.."[[Category:Automated article-slideshow portals with embedded list]]"endifusesEponymousArticlethenretval=retval.."[[Category:Automated article-slideshow portals with article list built using eponymous article]]"endreturnretvalendfunctionarrayvalues(t)locali=0returnfunction()i=i+1;returnt[i]endend-- end BHG addition for tracking source pagesreturnp
close