wiki.pl 156 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082
  1. #! /usr/bin/perl
  2. # Copyright (C) 2001-2015
  3. # Alex Schroeder <alex@gnu.org>
  4. # Copyright (C) 2014-2015
  5. # Alex Jakimenko <alex.jakimenko@gmail.com>
  6. # Copyleft 2008 Brian Curry <http://www.raiazome.com>
  7. # ... including lots of patches from the UseModWiki site
  8. # Copyright (C) 2001, 2002 various authors
  9. # ... which was based on UseModWiki version 0.92 (April 21, 2001)
  10. # Copyright (C) 2000, 2001 Clifford A. Adams
  11. # <caadams@frontiernet.net> or <usemod@usemod.com>
  12. # ... which was based on the GPLed AtisWiki 0.3
  13. # Copyright (C) 1998 Markus Denker <marcus@ira.uka.de>
  14. # ... which was based on the LGPLed CVWiki CVS-patches
  15. # Copyright (C) 1997 Peter Merel
  16. # ... and The Original WikiWikiWeb
  17. # Copyright (C) 1996, 1997 Ward Cunningham <ward@c2.com>
  18. # (code reused with permission)
  19. # This program is free software: you can redistribute it and/or modify it under
  20. # the terms of the GNU General Public License as published by the Free Software
  21. # Foundation, either version 3 of the License, or (at your option) any later
  22. # version.
  23. #
  24. # This program is distributed in the hope that it will be useful, but WITHOUT
  25. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  26. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  27. #
  28. # You should have received a copy of the GNU General Public License along with
  29. # this program. If not, see <http://www.gnu.org/licenses/>.
  30. package OddMuse;
  31. use strict;
  32. use warnings;
  33. no warnings 'numeric';
  34. no warnings 'uninitialized';
  35. use utf8; # in case anybody ever adds UTF8 characters to the source
  36. use CGI qw/-utf8/;
  37. use CGI::Carp qw(fatalsToBrowser);
  38. use File::Glob ':glob';
  39. use sigtrap 'handler' => \&HandleSignals, 'normal-signals', 'error-signals';
  40. local $| = 1; # Do not buffer output (localized for mod_perl)
  41. # Options:
  42. our ($ScriptName, $FullUrl, $PageDir, $TempDir, $LockDir, $KeepDir, $RssDir,
  43. $RcFile, $RcOldFile, $IndexFile, $NoEditFile, $VisitorFile, $DeleteFile, $RssLicense,
  44. $FreeLinkPattern, $LinkPattern, $FreeInterLinkPattern, $InterLinkPattern,
  45. $UrlPattern, $FullUrlPattern, $InterSitePattern,
  46. $UrlProtocols, $ImageExtensions, $LastUpdate,
  47. %LockOnCreation, %PlainTextPages, %AdminPages,
  48. @MyAdminCode, @MyFormChanges, @MyInitVariables, @MyMacros, @MyMaintenance,
  49. $DocumentHeader, %HtmlEnvironmentContainers, $FS, $Counter, @Debugging);
  50. # Internal variables:
  51. our ($q, $bol, $OpenPageName, %Page, %Translate, %IndexHash, @IndexList,
  52. @HtmlStack, @HtmlAttrStack, @Blocks, @Flags,
  53. %Includes, $FootnoteNumber, $CollectingJournal, $HeaderIsPrinted,
  54. %Locks, $Fragment, $Today, $ModulesDescription, %RssInterwikiTranslate,
  55. $Message, $Now, %RecentVisitors, %MyInc, $WikiDescription, %InterSite, %OldCookie);
  56. # Can be set outside the script: $DataDir, $UseConfig, $ConfigFile, $ModuleDir,
  57. # $ConfigPage, $AdminPass, $EditPass, $ScriptName, $FullUrl, $RunCGI.
  58. # 1 = load config file in the data directory
  59. our $UseConfig //= 1;
  60. # Main wiki directory
  61. our $DataDir;
  62. $DataDir ||= $ENV{WikiDataDir} if $UseConfig;
  63. $DataDir ||= '/tmp/oddmuse'; # FIXME: /var/opt/oddmuse/wiki ?
  64. our $ConfigFile;
  65. $ConfigFile ||= $ENV{WikiConfigFile} if $UseConfig;
  66. our $ModuleDir;
  67. $ModuleDir ||= $ENV{WikiModuleDir} if $UseConfig;
  68. our $ConfigPage ||= '';
  69. # 1 = Run script as CGI instead of loading as module
  70. our $RunCGI //= 1;
  71. # 1 = allow page views using wiki.pl/PageName
  72. our $UsePathInfo = 1;
  73. # -1 = disabled, 0 = 10s; 1 = partial HTML cache; 2 = HTTP/1.1 caching
  74. our $UseCache = 2;
  75. our $SiteName = 'Wiki'; # Name of site (used for titles)
  76. our $HomePage = 'HomePage'; # Home page
  77. our $CookieName = 'Wiki'; # Name for this wiki (for multi-wiki sites)
  78. our $MaxPost = 1024 * 210; # Maximum 210K posts (about 200K for pages)
  79. our $StyleSheet = ''; # URL for CSS stylesheet (like '/wiki.css')
  80. our $StyleSheetPage = ''; # Page for CSS sheet
  81. our $LogoUrl = ''; # URL for site logo ('' for no logo)
  82. our $NotFoundPg = ''; # Page for not-found links ('' for blank pg)
  83. our $EditAllowed = 1; # 0 = no, 1 = yes, 2 = comments pages only, 3 = comments only
  84. our $AdminPass //= ''; # Whitespace separated passwords.
  85. our $EditPass //= ''; # Whitespace separated passwords.
  86. our $PassHashFunction //= ''; # Name of the function to create hashes
  87. our $PassSalt //= ''; # Salt will be added to any password before hashing
  88. our $BannedHosts = 'BannedHosts'; # Page for banned hosts
  89. our $BannedCanRead = 1; # 1 = banned cannot edit, 0 = banned cannot read
  90. our $BannedContent = 'BannedContent'; # Page for banned content (usually for link-ban)
  91. our $WikiLinks = ''; # 1 = LinkPattern is a link
  92. our $FreeLinks = 1; # 1 = [[some text]] is a link
  93. our $UseQuestionmark = 1; # 1 = append questionmark to links to nonexisting pages
  94. our $BracketText = 1; # 1 = [URL desc] uses a description for the URL
  95. our $BracketWiki = 1; # 1 = [WikiLink desc] uses a desc for the local link
  96. our $NetworkFile = 1; # 1 = file: is a valid protocol for URLs
  97. our $AllNetworkFiles = 0; # 1 = file:///foo is allowed -- the default allows only file://foo
  98. our $InterMap = 'InterMap'; # name of the intermap page, '' = disable
  99. our $RssInterwikiTranslate = 'RssInterwikiTranslate'; # name of RSS interwiki translation page, '' = disable
  100. $ENV{PATH} = '/bin:/usr/bin'; # Path used to find 'diff' and 'grep'
  101. our $UseDiff = 1; # 1 = use diff
  102. our $SurgeProtection = 1; # 1 = protect against leeches
  103. our $SurgeProtectionTime = 20; # Size of the protected window in seconds
  104. our $SurgeProtectionViews = 20; # How many page views to allow in this window
  105. our $DeletedPage = 'DeletedPage'; # Pages starting with this can be deleted
  106. our $RCName = 'RecentChanges'; # Name of changes page
  107. our @RcDays = qw(1 3 7 30 90); # Days for links on RecentChanges
  108. our $RcDefault = 30; # Default number of RecentChanges days
  109. our $KeepDays = 0; # Days to keep old revisions (0 means keep forever)
  110. our $KeepMajor = 1; # 1 = keep at least one major rev when expiring pages
  111. our $SummaryHours = 4; # Hours to offer the old subject when editing a page
  112. our $SummaryDefaultLength = 150; # Length of default text for summary (0 to disable)
  113. our $ShowEdits = 0; # 1 = major and show minor edits in recent changes
  114. our $ShowAll = 0; # 1 = show multiple edits per page in recent changes
  115. our $ShowRollbacks = 0; # 1 = show rollbacks in recent changes
  116. our $RecentLink = 1; # 1 = link to usernames
  117. our $PageCluster = ''; # name of cluster page, eg. 'Cluster' to enable
  118. our $InterWikiMoniker = ''; # InterWiki prefix for this wiki for RSS
  119. our $SiteDescription = ''; # RSS Description of this wiki
  120. our $RssStrip = '^\d\d\d\d-\d\d-\d\d_'; # Regexp to strip from feed item titles
  121. our $RssImageUrl = $LogoUrl; # URL to image to associate with your RSS feed
  122. our $RssRights = ''; # Copyright notice for RSS, usually an URL to the appropriate text
  123. our $RssExclude = 'RssExclude'; # name of the page that lists pages to be excluded from the feed
  124. our $RssCacheHours = 1; # How many hours to cache remote RSS files
  125. our $RssStyleSheet = ''; # External style sheet for RSS files
  126. our $UploadAllowed = 0; # 1 = yes, 0 = administrators only
  127. our @UploadTypes = ('image/jpeg', 'image/png'); # MIME types allowed, all allowed if empty list
  128. our $EmbedWiki = 0; # 1 = no headers/footers
  129. our $FooterNote = ''; # HTML for bottom of every page
  130. our $EditNote = ''; # HTML notice above buttons on edit page
  131. our $TopLinkBar = 1; # 0 = goto bar both at the top and bottom; 1 = top, 2 = bottom
  132. our $TopSearchForm = 1; # 0 = search form both at the top and bottom; 1 = top, 2 = bottom
  133. our $MatchingPages = 0; # 1 = search page content and page titles
  134. our @UserGotoBarPages = (); # List of pagenames
  135. our $UserGotoBar = ''; # HTML added to end of goto bar
  136. our $CommentsPrefix = ''; # prefix for comment pages, eg. 'Comments_on_' to enable
  137. our $CommentsPattern = undef; # regex used to match comment pages
  138. our $HtmlHeaders = ''; # Additional stuff to put in the HTML <head> section
  139. our $IndentLimit = 20; # Maximum depth of nested lists
  140. our $LanguageLimit = 3; # Number of matches req. for each language
  141. our $JournalLimit = 200; # how many pages can be collected in one go?
  142. our $PageNameLimit = 120; # max length of page name in bytes
  143. $DocumentHeader = qq(<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN")
  144. . qq( "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n)
  145. . qq(<html xmlns="http://www.w3.org/1999/xhtml">);
  146. our @MyFooters = (\&GetCommentForm, \&WrapperEnd, \&DefaultFooter);
  147. # Checkboxes at the end of the index.
  148. our @IndexOptions = ();
  149. # Display short comments below the GotoBar for special days
  150. # Example: %SpecialDays = ('1-1' => 'New Year', '1-2' => 'Next Day');
  151. our %SpecialDays = ();
  152. # Replace regular expressions with inlined images
  153. # Example: %Smilies = (":-?D(?=\\W)" => '/pics/grin.png');
  154. our %Smilies = ();
  155. # Detect page languages when saving edits
  156. # Example: %Languages = ('de' => '\b(der|die|das|und|oder)\b');
  157. our %Languages = ();
  158. our @KnownLocks = qw(main diff index merge visitors); # locks to remove
  159. our $LockExpiration = 60; # How long before expirable locks are expired
  160. our %LockExpires = (diff=>1, index=>1, merge=>1, visitors=>1); # locks to expire after some time
  161. our %LockCleaners = (); # What to do if a job under a lock gets a signal like SIGINT. e.g. 'diff' => \&CleanDiff
  162. our %CookieParameters = (username=>'', pwd=>'', homepage=>'', theme=>'', css=>'', msg=>'', lang=>'', embed=>$EmbedWiki,
  163. toplinkbar=>$TopLinkBar, topsearchform=>$TopSearchForm, matchingpages=>$MatchingPages, );
  164. our %Action = (rc => \&BrowseRc, rollback => \&DoRollback,
  165. browse => \&BrowseResolvedPage, maintain => \&DoMaintain,
  166. random => \&DoRandom, pagelock => \&DoPageLock,
  167. history => \&DoHistory, editlock => \&DoEditLock,
  168. edit => \&DoEdit, version => \&DoShowVersion,
  169. download => \&DoDownload, rss => \&DoRss,
  170. unlock => \&DoUnlock, password => \&DoPassword,
  171. index => \&DoIndex, admin => \&DoAdminPage,
  172. clear => \&DoClearCache, debug => \&DoDebug,
  173. contrib => \&DoContributors, more => \&DoJournal);
  174. our @MyRules = (\&LinkRules, \&ListRule); # don't set this variable, add to it!
  175. our %RuleOrder = (\&LinkRules => 0, \&ListRule => 0);
  176. # The 'main' program, called at the end of this script file (aka. as handler)
  177. sub DoWikiRequest {
  178. Init();
  179. DoSurgeProtection();
  180. if (not $BannedCanRead and UserIsBanned() and not UserIsEditor()) {
  181. ReportError(T('Reading not allowed: user, ip, or network is blocked.'), '403 FORBIDDEN',
  182. 0, $q->p(ScriptLink('action=password', T('Login'), 'password')));
  183. }
  184. DoBrowseRequest();
  185. }
  186. sub ReportError { # fatal!
  187. my ($errmsg, $status, $log, @html) = @_;
  188. InitRequest(); # make sure we can report errors before InitRequest
  189. print GetHttpHeader('text/html', 'nocache', $status), GetHtmlHeader(T('Error')),
  190. $q->start_div({class=>"error"}), $q->h1(QuoteHtml($errmsg)), @html, $q->end_div,
  191. $q->end_html, "\n\n"; # newlines for FCGI because of exit()
  192. WriteStringToFile("$TempDir/error", '<body>' . $q->h1("$status $errmsg") . $q->Dump) if $log;
  193. map { ReleaseLockDir($_); } keys %Locks;
  194. exit 2;
  195. }
  196. sub Init {
  197. binmode(STDOUT, ':encoding(UTF-8)'); # this is where the HTML gets printed
  198. binmode(STDERR, ':encoding(UTF-8)'); # just in case somebody prints debug info to stderr
  199. InitDirConfig();
  200. $FS = "\x1e"; # The FS character is the RECORD SEPARATOR control char in ASCII
  201. $Message = ''; # Warnings and non-fatal errors.
  202. InitLinkPatterns(); # Link pattern can be changed in config files
  203. InitModules(); # Modules come first so that users can change module variables in config
  204. InitConfig(); # Config comes as early as possible; remember $q is not available here
  205. InitRequest(); # get $q with $MaxPost; set these in the config file
  206. InitCookie(); # After InitRequest, because $q is used
  207. InitVariables(); # After config, to change variables, after InitCookie for GetParam
  208. }
  209. sub InitModules {
  210. if ($UseConfig and $ModuleDir and -d $ModuleDir) {
  211. foreach my $lib (bsd_glob("$ModuleDir/*.p[ml]")) {
  212. do $lib unless $MyInc{$lib};
  213. $MyInc{$lib} = 1; # Cannot use %INC in mod_perl settings
  214. $Message .= CGI::p("$lib: $@") if $@; # no $q exists, yet
  215. }
  216. }
  217. }
  218. sub InitConfig {
  219. if ($UseConfig and $ConfigFile and not $INC{$ConfigFile} and -f $ConfigFile) {
  220. do $ConfigFile; # these options must be set in a wrapper script or via the environment
  221. $Message .= CGI::p("$ConfigFile: $@") if $@; # remember, no $q exists, yet
  222. }
  223. if ($ConfigPage) { # $FS and $MaxPost must be set in config file!
  224. my ($status, $data) = ReadFile(GetPageFile(FreeToNormal($ConfigPage)));
  225. my $page = ParseData($data); # before InitVariables so GetPageContent won't work
  226. eval $page->{text} if $page->{text}; # perlcritic dislikes the use of eval here but we really mean it
  227. $Message .= CGI::p("$ConfigPage: $@") if $@;
  228. }
  229. }
  230. sub InitDirConfig {
  231. utf8::decode($DataDir); # just in case, eg. "WikiDataDir=/tmp/Zürich♥ perl wiki.pl"
  232. $PageDir = "$DataDir/page"; # Stores page data
  233. $KeepDir = "$DataDir/keep"; # Stores kept (old) page data
  234. $TempDir = "$DataDir/temp"; # Temporary files and locks
  235. $LockDir = "$TempDir/lock"; # DB is locked if this exists
  236. $NoEditFile = "$DataDir/noedit"; # Indicates that the site is read-only
  237. $RcFile = "$DataDir/rc.log"; # New RecentChanges logfile
  238. $RcOldFile = "$DataDir/oldrc.log"; # Old RecentChanges logfile
  239. $IndexFile = "$DataDir/pageidx"; # List of all pages
  240. $VisitorFile = "$DataDir/visitors.log"; # List of recent visitors
  241. $DeleteFile = "$DataDir/delete.log"; # Deletion logfile
  242. $RssDir = "$DataDir/rss"; # For rss feed cache
  243. $ConfigFile ||= "$DataDir/config"; # Config file with Perl code to execute
  244. $ModuleDir ||= "$DataDir/modules"; # For extensions (ending in .pm or .pl)
  245. }
  246. sub InitRequest { # set up $q
  247. $CGI::POST_MAX = $MaxPost;
  248. $q ||= new CGI;
  249. }
  250. sub InitVariables { # Init global session variables for mod_perl!
  251. $WikiDescription = $q->p($q->a({-href=>'http://www.oddmuse.org/'}, 'Oddmuse'),
  252. $Counter++ > 0 ? Ts('%s calls', $Counter) : '');
  253. $WikiDescription .= $ModulesDescription if $ModulesDescription;
  254. $HeaderIsPrinted = 0; # print HTTP headers only once
  255. $ScriptName //= $q->url(); # URL used in links
  256. $FullUrl ||= $ScriptName; # URL used in forms
  257. %Locks = ();
  258. @Blocks = ();
  259. @Flags = ();
  260. $Fragment = '';
  261. %RecentVisitors = ();
  262. $OpenPageName = ''; # Currently open page
  263. my $add_space = $CommentsPrefix =~ /[ \t_]$/;
  264. $$_ = FreeToNormal($$_) for # convert spaces to underscores on all configurable pagenames
  265. (\$HomePage, \$RCName, \$BannedHosts, \$InterMap, \$StyleSheetPage, \$CommentsPrefix,
  266. \$ConfigPage, \$NotFoundPg, \$RssInterwikiTranslate, \$BannedContent, \$RssExclude, );
  267. $CommentsPrefix .= '_' if $add_space;
  268. $CommentsPattern = "^$CommentsPrefix(.*)" unless defined $CommentsPattern or not $CommentsPrefix;
  269. @UserGotoBarPages = ($HomePage, $RCName) unless @UserGotoBarPages;
  270. my @pages = sort($BannedHosts, $StyleSheetPage, $ConfigPage, $InterMap,
  271. $RssInterwikiTranslate, $BannedContent);
  272. %AdminPages = map { $_ => 1} @pages, $RssExclude unless %AdminPages;
  273. %LockOnCreation = map { $_ => 1} @pages unless %LockOnCreation;
  274. %PlainTextPages = ($BannedHosts => 1, $BannedContent => 1,
  275. $StyleSheetPage => 1, $ConfigPage => 1) unless %PlainTextPages;
  276. delete $PlainTextPages{''}; # $ConfigPage and others might be empty.
  277. CreateDir($DataDir); # Create directory if it doesn't exist
  278. $Now = time; # Reset in case script is persistent
  279. my $ts = (stat($IndexFile))[9]; # always stat for multiple server processes
  280. ReInit() if not $ts or $LastUpdate != $ts; # reinit if another process changed files (requires $DataDir)
  281. $LastUpdate = $ts;
  282. unshift(@MyRules, \&MyRules) if defined(&MyRules) && (not @MyRules or $MyRules[0] != \&MyRules);
  283. @MyRules = sort {$RuleOrder{$a} <=> $RuleOrder{$b}} @MyRules; # default is 0
  284. @IndexOptions = (['pages', T('Include normal pages'), 1, \&AllPagesList]);
  285. foreach my $sub (@MyInitVariables) {
  286. my $result = $sub->();
  287. $Message .= $q->p($@) if $@;
  288. }
  289. }
  290. sub ReInit { # init everything we need if we want to link to stuff
  291. my $id = shift; # when saving a page, what to do depends on the page being saved
  292. AllPagesList() unless $id;
  293. InterInit() if $InterMap and (not $id or $id eq $InterMap);
  294. %RssInterwikiTranslate = () if not $id or $id eq $RssInterwikiTranslate; # special since rarely used
  295. }
  296. sub InitCookie {
  297. undef $q->{'.cookies'}; # Clear cache if it exists (for SpeedyCGI)
  298. my $cookie = $q->cookie($CookieName);
  299. %OldCookie = split(/$FS/, UrlDecode($cookie));
  300. my %provided = map { $_ => 1 } $q->param;
  301. for my $key (keys %OldCookie) {
  302. SetParam($key, $OldCookie{$key}) unless $provided{$key};
  303. }
  304. CookieUsernameFix();
  305. CookieRollbackFix();
  306. }
  307. sub CookieUsernameFix {
  308. # Only valid usernames get stored in the new cookie.
  309. my $name = GetParam('username', '');
  310. $q->delete('username');
  311. if (not $name) {
  312. # do nothing
  313. } elsif ($WikiLinks and not $FreeLinks and $name !~ /^$LinkPattern$/) {
  314. $Message .= $q->p(Ts('Invalid UserName %s: not saved.', $name));
  315. } elsif ($FreeLinks and $name !~ /^$FreeLinkPattern$/) {
  316. $Message .= $q->p(Ts('Invalid UserName %s: not saved.', $name));
  317. } elsif (length($name) > 50) { # Too long
  318. $Message .= $q->p(T('UserName must be 50 characters or less: not saved'));
  319. } else {
  320. SetParam('username', $name);
  321. }
  322. }
  323. sub CookieRollbackFix {
  324. my @rollback = grep(/rollback-(\d+)/, $q->param);
  325. if (@rollback and $rollback[0] =~ /(\d+)/) {
  326. SetParam('to', $1);
  327. $q->delete('action');
  328. SetParam('action', 'rollback');
  329. }
  330. }
  331. sub GetParam {
  332. my ($name, $default) = @_;
  333. utf8::encode($name); # turn to byte string
  334. my $result = $q->param($name);
  335. $result //= $default;
  336. return QuoteHtml($result); # you need to unquote anything that can have <tags>
  337. }
  338. sub SetParam {
  339. my ($name, $val) = @_;
  340. $q->param($name, $val);
  341. }
  342. sub InitLinkPatterns {
  343. my ($WikiWord, $QDelim);
  344. $QDelim = '(?:"")?'; # Optional quote delimiter (removed from the output)
  345. $WikiWord = '\p{Uppercase}+\p{Lowercase}+\p{Uppercase}\p{Alphabetic}*';
  346. $LinkPattern = "($WikiWord)$QDelim";
  347. $FreeLinkPattern = "([-,.()'%&?;<> _1-9A-Za-z\x{0080}-\x{fffd}]|[-,.()'%&?;<> _0-9A-Za-z\x{0080}-\x{fffd}][-,.()'%&?;<> _0-9A-Za-z\x{0080}-\x{fffd}]+)"; # disallow "0" and must match HTML and plain text (ie. > and &gt;)
  348. # Intersites must start with uppercase letter to avoid confusion with URLs.
  349. $InterSitePattern = '[A-Z\x{0080}-\x{fffd}]+[A-Za-z\x{0080}-\x{fffd}]+';
  350. $InterLinkPattern = "($InterSitePattern:[-a-zA-Z0-9\x{0080}-\x{fffd}_=!?#\$\@~`\%&*+\\/:;.,]*[-a-zA-Z0-9\x{0080}-\x{fffd}_=#\$\@~`\%&*+\\/])$QDelim";
  351. $FreeInterLinkPattern = "($InterSitePattern:[-a-zA-Z0-9\x{0080}-\x{fffd}_=!?#\$\@~`\%&*+\\/:;.,()' ]+)"; # plus space and other characters, and no restrictions on the end of the pattern
  352. $UrlProtocols = 'http|https|ftp|afs|news|nntp|mid|cid|mailto|wais|prospero|telnet|gopher|irc|feed';
  353. $UrlProtocols .= '|file' if $NetworkFile;
  354. my $UrlChars = '[-a-zA-Z0-9/@=+$_~*.,;:?!\'"()&#%]'; # see RFC 2396
  355. my $EndChars = '[-a-zA-Z0-9/@=+$_~*]'; # no punctuation at the end of the url.
  356. $UrlPattern = "((?:$UrlProtocols):$UrlChars+$EndChars)";
  357. $FullUrlPattern="((?:$UrlProtocols):$UrlChars+)"; # when used in square brackets
  358. $ImageExtensions = '(gif|jpg|jpeg|png|bmp|svg)';
  359. }
  360. sub Clean {
  361. my $block = shift;
  362. return 0 unless defined($block); # "0" must print
  363. return 1 if $block eq ''; # '' is the result of a dirty rule
  364. $Fragment .= $block;
  365. return 1;
  366. }
  367. sub Dirty { # arg 1 is the raw text; the real output must be printed instead
  368. if ($Fragment ne '') {
  369. $Fragment =~ s|<p>\s*</p>||g; # clean up extra paragraphs (see end of ApplyRules)
  370. print $Fragment;
  371. push(@Blocks, $Fragment);
  372. push(@Flags, 0);
  373. }
  374. push(@Blocks, shift);
  375. push(@Flags, 1);
  376. $Fragment = '';
  377. }
  378. sub ApplyRules {
  379. # locallinks: apply rules that create links depending on local config (incl. interlink!)
  380. my ($text, $locallinks, $withanchors, $revision, @tags) = @_; # $revision is used for images
  381. $text =~ s/\r\n/\n/g; # DOS to Unix
  382. $text =~ s/\n+$//g; # No trailing paragraphs
  383. return if $text eq ''; # allow the text '0'
  384. local $Fragment = ''; # the clean HTML fragment not yet on @Blocks
  385. local @Blocks = (); # the list of cached HTML blocks
  386. local @Flags = (); # a list for each block, 1 = dirty, 0 = clean
  387. Clean(join('', map { AddHtmlEnvironment($_) } @tags));
  388. if ($OpenPageName and $PlainTextPages{$OpenPageName}) { # there should be no $PlainTextPages{''}
  389. Clean(CloseHtmlEnvironments() . $q->pre($text));
  390. } elsif (my ($type) = TextIsFile($text)) { # TODO? $type defined here??
  391. Clean(CloseHtmlEnvironments() . $q->p(T('This page contains an uploaded file:'))
  392. . $q->p(GetDownloadLink($OpenPageName, (substr($type, 0, 6) eq 'image/'), $revision))
  393. . (length $Page{summary} > 0 ? $q->blockquote(QuoteHtml($Page{summary})) : $q->p(T('No summary was provided for this file.'))));
  394. } else {
  395. my $smileyregex = join "|", keys %Smilies;
  396. $smileyregex = qr/(?=$smileyregex)/;
  397. local $_ = $text;
  398. local $bol = 1;
  399. while (1) {
  400. # Block level elements should eat trailing empty lines to prevent empty p elements.
  401. if ($bol and m/\G(\s*\n)+/cg) {
  402. Clean(CloseHtmlEnvironments() . AddHtmlEnvironment('p'));
  403. } elsif ($bol and m/\G(\&lt;include(\s+(text|with-anchors))?\s+"(.*)"\&gt;[ \t]*\n?)/cgi) {
  404. # <include "uri..."> includes the text of the given URI verbatim
  405. Clean(CloseHtmlEnvironments());
  406. Dirty($1);
  407. my ($oldpos, $old_, $type, $uri) = ((pos), $_, $3, UnquoteHtml($4)); # remember, page content is quoted!
  408. if ($uri =~ /^($UrlProtocols):/) {
  409. if ($type eq 'text') {
  410. print $q->pre({class=>"include $uri"}, QuoteHtml(GetRaw($uri)));
  411. } else { # never use local links for remote pages, with a starting tag
  412. print $q->start_div({class=>"include"});
  413. ApplyRules(QuoteHtml(GetRaw($uri)), 0, ($type eq 'with-anchors'), undef, 'p');
  414. print $q->end_div();
  415. }
  416. } else {
  417. $Includes{$OpenPageName} = 1;
  418. local $OpenPageName = FreeToNormal($uri);
  419. if ($type eq 'text') {
  420. print $q->pre({class=>"include $OpenPageName"}, QuoteHtml(GetPageContent($OpenPageName)));
  421. } elsif (not $Includes{$OpenPageName}) { # with a starting tag, watch out for recursion
  422. print $q->start_div({class=>"include $OpenPageName"});
  423. ApplyRules(QuoteHtml(GetPageContent($OpenPageName)), $locallinks, $withanchors, undef, 'p');
  424. print $q->end_div();
  425. delete $Includes{$OpenPageName};
  426. } else {
  427. print $q->p({-class=>'error'}, $q->strong(Ts('Recursive include of %s!', $OpenPageName)));
  428. }
  429. }
  430. Clean(AddHtmlEnvironment('p')); # if dirty block is looked at later, this will disappear
  431. ($_, pos) = ($old_, $oldpos); # restore \G (assignment order matters!)
  432. } elsif ($bol and m/\G(\&lt;(journal|titles):?(\d*)((\s+|:)(\d*),?(\d*))?(\s+"(.*?)")?(\s+(reverse|past|future))?(\s+search\s+(.*))?\&gt;[ \t]*\n?)/cgi) {
  433. # <journal 10 "regexp"> includes 10 pages matching regexp
  434. Clean(CloseHtmlEnvironments());
  435. Dirty($1);
  436. my ($oldpos, $old_) = (pos, $_); # remember these because of the call to PrintJournal()
  437. PrintJournal($6, $7, $9, $11, $3, $13, $2);
  438. Clean(AddHtmlEnvironment('p')); # if dirty block is looked at later, this will disappear
  439. ($_, pos) = ($old_, $oldpos); # restore \G (assignment order matters!)
  440. } elsif ($bol and m/\G(\&lt;rss(\s+(\d*))?\s+(.*?)\&gt;[ \t]*\n?)/cgis) {
  441. # <rss "uri..."> stores the parsed RSS of the given URI
  442. Clean(CloseHtmlEnvironments());
  443. Dirty($1);
  444. my ($oldpos, $old_) = (pos, $_); # remember these because of the call to RSS()
  445. print RSS($3 || 15, split(/\s+/, UnquoteHtml($4)));
  446. Clean(AddHtmlEnvironment('p')); # if dirty block is looked at later, this will disappear
  447. ($_, pos) = ($old_, $oldpos); # restore \G (assignment order matters!)
  448. } elsif (/\G(&lt;search (.*?)&gt;)/cgis) {
  449. # <search regexp>
  450. Clean(CloseHtmlEnvironments());
  451. Dirty($1);
  452. my ($oldpos, $old_) = (pos, $_);
  453. print $q->start_div({-class=>'search'});
  454. SearchTitleAndBody($2, \&PrintSearchResult, SearchRegexp($2));
  455. print $q->end_div;
  456. Clean(AddHtmlEnvironment('p')); # if dirty block is looked at later, this will disappear
  457. ($_, pos) = ($old_, $oldpos); # restore \G (assignment order matters!)
  458. } elsif ($bol and m/\G(&lt;&lt;&lt;&lt;&lt;&lt;&lt; )/cg) {
  459. my ($str, $count, $limit, $oldpos) = ($1, 0, 100, pos);
  460. while (m/\G(.*\n)/cg and $count++ < $limit) {
  461. $str .= $1;
  462. last if (substr($1, 0, 29) eq '&gt;&gt;&gt;&gt;&gt;&gt;&gt; ');
  463. }
  464. if ($count >= $limit) {
  465. pos = $oldpos; # reset because we did not find a match
  466. Clean('&lt;&lt;&lt;&lt;&lt;&lt;&lt; ');
  467. } else {
  468. Clean(CloseHtmlEnvironments() . $q->pre({-class=>'conflict'}, $str) . AddHtmlEnvironment('p'));
  469. }
  470. } elsif ($bol and m/\G#REDIRECT/cg) {
  471. Clean('#REDIRECT');
  472. } elsif (%Smilies and m/\G$smileyregex/cg and Clean(SmileyReplace())) {
  473. } elsif (Clean(RunMyRules($locallinks, $withanchors))) {
  474. } elsif (m/\G\s*\n(\s*\n)+/cg) { # paragraphs: at least two newlines
  475. Clean(CloseHtmlEnvironments() . AddHtmlEnvironment('p')); # another one like this further up
  476. } elsif (m/\G&amp;([A-Za-z]+|#[0-9]+|#x[A-Za-f0-9]+);/cg) { # entity references
  477. Clean("&$1;");
  478. } elsif (m/\G\s+/cg) {
  479. Clean(' ');
  480. } elsif (m/\G([A-Za-z\x{0080}-\x{fffd}]+([ \t]+[a-z\x{0080}-\x{fffd}]+)*[ \t]+)/cg
  481. or m/\G([A-Za-z\x{0080}-\x{fffd}]+)/cg or m/\G(\S)/cg) {
  482. Clean($1); # multiple words but do not match http://foo
  483. } else {
  484. last;
  485. }
  486. $bol = (substr($_, pos() - 1, 1) eq "\n");
  487. }
  488. }
  489. pos = length $_; # notify module functions we've completed rule handling
  490. Clean(CloseHtmlEnvironments()); # last block -- close it, cache it
  491. if ($Fragment ne '') {
  492. $Fragment =~ s|<p>\s*</p>||g; # clean up extra paragraphs (see end Dirty())
  493. print $Fragment;
  494. push(@Blocks, $Fragment);
  495. push(@Flags, 0);
  496. }
  497. # this can be stored in the page cache -- see PrintCache
  498. return (join($FS, @Blocks), join($FS, @Flags));
  499. }
  500. sub ListRule {
  501. if ($bol && m/\G(\s*\n)*(\*+)[ \t]+/cg
  502. or InElement('li') && m/\G(\s*\n)+(\*+)[ \t]+/cg) {
  503. return CloseHtmlEnvironmentUntil('li')
  504. . OpenHtmlEnvironment('ul', length($2)) . AddHtmlEnvironment('li');
  505. }
  506. return;
  507. }
  508. sub LinkRules {
  509. my ($locallinks, $withanchors) = @_;
  510. if ($locallinks
  511. and ($BracketText && m/\G(\[$InterLinkPattern\s+([^\]]+?)\])/cg
  512. or $BracketText && m/\G(\[\[$FreeInterLinkPattern\|([^\]]+?)\]\])/cg
  513. or m/\G(\[$InterLinkPattern\])/cg or m/\G(\[\[\[$FreeInterLinkPattern\]\]\])/cg
  514. or m/\G($InterLinkPattern)/cg or m/\G(\[\[$FreeInterLinkPattern\]\])/cg)) {
  515. # [InterWiki:FooBar text] or [InterWiki:FooBar] or
  516. # InterWiki:FooBar or [[InterWiki:foo bar|text]] or
  517. # [[InterWiki:foo bar]] or [[[InterWiki:foo bar]]]-- Interlinks
  518. # can change when the intermap changes (local config, therefore
  519. # depend on $locallinks). The intermap is only read if
  520. # necessary, so if this not an interlink, we have to backtrack a
  521. # bit.
  522. my $bracket = (substr($1, 0, 1) eq '[') # but \[\[$FreeInterLinkPattern\]\] it not bracket!
  523. && !((substr($1, 0, 2) eq '[[') && (substr($1, 2, 1) ne '[') && index($1, '|') < 0);
  524. my $quote = (substr($1, 0, 2) eq '[[');
  525. my ($oldmatch, $output) = ($1, GetInterLink($2, $3, $bracket, $quote)); # $3 may be empty
  526. if ($oldmatch eq $output) { # no interlink
  527. my ($site, $rest) = split(/:/, $oldmatch, 2);
  528. Clean($site);
  529. pos = (pos) - length($rest) - 1; # skip site, but reparse rest
  530. } else {
  531. Dirty($oldmatch);
  532. print $output; # this is an interlink
  533. }
  534. } elsif ($BracketText && m/\G(\[$FullUrlPattern[|[:space:]]([^\]]+?)\])/cg
  535. or $BracketText && m/\G(\[\[$FullUrlPattern[|[:space:]]([^\]]+?)\]\])/cg
  536. or m/\G(\[$FullUrlPattern\])/cg or m/\G($UrlPattern)/cg) {
  537. # [URL text] makes [text] link to URL, [URL] makes footnotes [1]
  538. my ($str, $url, $text, $bracket, $rest) = ($1, $2, $3, (substr($1, 0, 1) eq '['), '');
  539. if ($url =~ /(&lt|&gt|&amp)$/) { # remove trailing partial named entitites and add them as
  540. $rest = $1; # back again at the end as trailing text.
  541. $url =~ s/&(lt|gt|amp)$//;
  542. }
  543. if ($bracket and not defined $text) { # [URL] is dirty because the number may change
  544. Dirty($str);
  545. print GetUrl($url, $text, $bracket), $rest;
  546. } else {
  547. Clean(GetUrl($url, $text, $bracket, not $bracket) . $rest); # $text may be empty, no images in brackets
  548. }
  549. } elsif ($WikiLinks && m/\G!$LinkPattern/cg) {
  550. Clean($1); # ! gets eaten
  551. } elsif ($WikiLinks && $locallinks
  552. && ($BracketWiki && m/\G(\[$LinkPattern\s+([^\]]+?)\])/cg
  553. or m/\G(\[$LinkPattern\])/cg or m/\G($LinkPattern)/cg)) {
  554. # [LocalPage text], [LocalPage], LocalPage
  555. Dirty($1);
  556. my $bracket = (substr($1, 0, 1) eq '[' and not $3);
  557. print GetPageOrEditLink($2, $3, $bracket);
  558. } elsif ($locallinks && $FreeLinks && (m/\G(\[\[image:$FreeLinkPattern\]\])/cg
  559. or m/\G(\[\[image:$FreeLinkPattern\|([^]|]+)\]\])/cg)) {
  560. # [[image:Free Link]], [[image:Free Link|alt text]]
  561. Dirty($1);
  562. print GetDownloadLink(FreeToNormal($2), 1, undef, UnquoteHtml($3));
  563. } elsif ($FreeLinks && $locallinks
  564. && ($BracketWiki && m/\G(\[\[$FreeLinkPattern\|([^\]]+)\]\])/cg
  565. or m/\G(\[\[\[$FreeLinkPattern\]\]\])/cg
  566. or m/\G(\[\[$FreeLinkPattern\]\])/cg)) {
  567. # [[Free Link|text]], [[[Free Link]]], [[Free Link]]
  568. Dirty($1);
  569. my $bracket = (substr($1, 0, 3) eq '[[[');
  570. print GetPageOrEditLink($2, $3, $bracket, 1); # $3 may be empty
  571. } else {
  572. return; # nothing matched
  573. }
  574. return ''; # one of the dirty rules matched (and they all are)
  575. }
  576. sub SetHtmlEnvironmentContainer {
  577. my ($html_tag, $html_tag_attr) = @_;
  578. $HtmlEnvironmentContainers{$html_tag} = defined $html_tag_attr ? (
  579. $HtmlEnvironmentContainers{$html_tag} ? '|' . $HtmlEnvironmentContainers{$html_tag} : '')
  580. . $html_tag_attr : '';
  581. }
  582. sub InElement { # is $html_tag in @HtmlStack?
  583. my ($html_tag, $html_tag_attr) = @_;
  584. my $i = 0;
  585. foreach my $html_tag_current (@HtmlStack) {
  586. return 1 if $html_tag_current eq $html_tag and
  587. ($html_tag_attr ? $HtmlAttrStack[$i] =~ m/$html_tag_attr/ : 1);
  588. $i++;
  589. } return '';
  590. }
  591. sub AddOrCloseHtmlEnvironment { # add $html_tag, if not already added; close, otherwise
  592. my ($html_tag, $html_tag_attr) = @_;
  593. return InElement ($html_tag, '^' . $html_tag_attr . '$')
  594. ? CloseHtmlEnvironment($html_tag, '^' . $html_tag_attr . '$')
  595. : AddHtmlEnvironment ($html_tag, $html_tag_attr);
  596. }
  597. sub AddHtmlEnvironment { # add a new $html_tag
  598. my ($html_tag, $html_tag_attr) = @_;
  599. $html_tag_attr //= '';
  600. if ($html_tag and not (@HtmlStack and $HtmlStack[0] eq $html_tag and
  601. ($html_tag_attr ? $HtmlAttrStack[0] =~ m/$html_tag_attr/ : 1))) {
  602. unshift(@HtmlStack, $html_tag);
  603. unshift(@HtmlAttrStack, $html_tag_attr);
  604. return '<' . $html_tag . ($html_tag_attr ? ' ' . $html_tag_attr : '') . '>';
  605. } return ''; # always return something
  606. }
  607. sub OpenHtmlEnvironment { # close the previous $html_tag and open a new one
  608. my ($html_tag, $depth, $html_tag_attr, $tag_regex) = @_;
  609. my ($html, $found, @stack) = ('', 0); # always return something
  610. while (@HtmlStack and $found < $depth) { # determine new stack
  611. my $tag = pop(@HtmlStack);
  612. $found++ if ($tag_regex ? $tag =~ $tag_regex : $tag eq $html_tag);
  613. unshift(@stack, $tag);
  614. }
  615. unshift(@stack, pop(@HtmlStack)) if @HtmlStack and $found < $depth; # nested sublist coming up, keep list item
  616. @HtmlStack = @stack unless $found; # if starting a new list
  617. $html .= CloseHtmlEnvironments(); # close remaining elements (or all elements if a new list)
  618. @HtmlStack = @stack if $found; # if not starting a new list
  619. $depth = $IndentLimit if $depth > $IndentLimit; # requested depth 0 makes no sense
  620. $html_tag_attr = qq/class="$html_tag_attr"/ # backwards-compatibility hack: classically, the third argument to this function was a single CSS class, rather than string of HTML tag attributes as in the second argument to the "AddHtmlEnvironment" function. To allow both sorts, we conditionally change this string to 'class="$html_tag_attr"' when this string is a single CSS class.
  621. if $html_tag_attr and $html_tag_attr !~ m/^\s*[[:alpha:]]@@+\s*=\s*('|").+\1/;
  622. splice(@HtmlAttrStack, 0, @HtmlAttrStack - @HtmlStack); # truncate to size of @HtmlStack
  623. foreach ($found .. $depth - 1) {
  624. unshift(@HtmlStack, $html_tag);
  625. unshift(@HtmlAttrStack, $html_tag_attr);
  626. $html .= $html_tag_attr ? "<$html_tag $html_tag_attr>" : "<$html_tag>";
  627. }
  628. return $html;
  629. }
  630. sub CloseHtmlEnvironments { # close all -- remember to use AddHtmlEnvironment('p') if required!
  631. return CloseHtmlEnvironmentUntil() if pos($_) == length($_); # close all HTML environments if we're are at the end of this page
  632. my $html = '';
  633. while (@HtmlStack) {
  634. defined $HtmlEnvironmentContainers{$HtmlStack[0]} and # avoid closing block level elements
  635. ($HtmlEnvironmentContainers{$HtmlStack[0]} ? $HtmlAttrStack[0] =~
  636. m/$HtmlEnvironmentContainers{$HtmlStack[0]}/ : 1) and return $html;
  637. shift(@HtmlAttrStack);
  638. $html .= '</' . shift(@HtmlStack) . '>';
  639. }
  640. return $html;
  641. }
  642. sub CloseHtmlEnvironment { # close environments up to and including $html_tag
  643. my $html = (@_ and InElement(@_)) ? CloseHtmlEnvironmentUntil(@_) : '';
  644. if (@HtmlStack and (not(@_) or defined $html)) {
  645. shift(@HtmlAttrStack);
  646. return $html . '</' . shift(@HtmlStack) . '>';
  647. }
  648. return $html || ''; # avoid returning undefined
  649. }
  650. sub CloseHtmlEnvironmentUntil { # close environments up to but not including $html_tag
  651. my ($html_tag, $html_tag_attr) = @_;
  652. my $html = '';
  653. while (@HtmlStack && (pos($_) == length($_) || # while there is an HTML tag-stack and we are at the end of this page or...
  654. !($html_tag ? $HtmlStack[0] eq $html_tag && # the top tag is not the desired tag and...
  655. ($html_tag_attr ? $HtmlAttrStack[0] =~ # its attributes do not match,
  656. m/$html_tag_attr/ : 1) : ''))) { # then...
  657. shift(@HtmlAttrStack); # shift off the top tag and
  658. $html .= '</' . shift(@HtmlStack) . '>'; # append it to our HTML string.
  659. }
  660. return $html;
  661. }
  662. sub SmileyReplace {
  663. foreach my $regexp (keys %Smilies) {
  664. if (m/\G($regexp)/cg) {
  665. return $q->img({-src=>$Smilies{$regexp}, -alt=>UnquoteHtml($1), -class=>'smiley'});
  666. }
  667. }
  668. }
  669. sub RunMyRules {
  670. my ($locallinks, $withanchors) = @_;
  671. foreach my $sub (@MyRules) {
  672. my $result = $sub->($locallinks, $withanchors);
  673. SetParam('msg', $@) if $@;
  674. return $result if defined($result);
  675. }
  676. return;
  677. }
  678. sub RunMyMacros {
  679. $_ = shift;
  680. foreach my $macro (@MyMacros) { $macro->() };
  681. return $_;
  682. }
  683. sub PrintWikiToHTML {
  684. my ($markup, $is_saving_cache, $revision, $is_locked) = @_;
  685. my ($blocks, $flags);
  686. $FootnoteNumber = 0;
  687. $markup =~ s/$FS//g if $markup; # Remove separators (paranoia)
  688. $markup = QuoteHtml($markup);
  689. ($blocks, $flags) = ApplyRules($markup, 1, $is_saving_cache, $revision, 'p');
  690. if ($is_saving_cache and not $revision and $Page{revision} # don't save revision 0 pages
  691. and $Page{blocks} ne $blocks and $Page{flags} ne $flags) {
  692. $Page{blocks} = $blocks;
  693. $Page{flags} = $flags;
  694. if ($is_locked or RequestLockDir('main')) { # not fatal!
  695. SavePage();
  696. ReleaseLock() unless $is_locked;
  697. }
  698. }
  699. }
  700. sub DoClearCache {
  701. return unless UserIsAdminOrError();
  702. RequestLockOrError();
  703. print GetHeader('', T('Clear Cache')), $q->start_div({-class=>'content clear'}),
  704. $q->p(T('Main lock obtained.')), '<p>';
  705. foreach my $id (AllPagesList()) {
  706. OpenPage($id);
  707. delete @Page{qw(blocks flags languages)};
  708. $Page{languages} = GetLanguages($Page{blocks}) unless TextIsFile($Page{blocks});
  709. SavePage();
  710. print $q->br(), GetPageLink($id);
  711. }
  712. print '</p>', $q->p(T('Main lock released.')), $q->end_div();
  713. utime time, time, $IndexFile; # touch index file
  714. ReleaseLock();
  715. PrintFooter();
  716. }
  717. sub QuoteHtml {
  718. my $html = shift;
  719. $html =~ s/&/&amp;/g;
  720. $html =~ s/</&lt;/g;
  721. $html =~ s/>/&gt;/g;
  722. $html =~ s/[\x00-\x08\x0b\x0c\x0e-\x1f]/ /g; # legal xml: #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
  723. return $html;
  724. }
  725. sub UnquoteHtml {
  726. my $html = shift;
  727. $html =~ s/&lt;/</g;
  728. $html =~ s/&gt;/>/g;
  729. $html =~ s/&amp;/&/g;
  730. $html =~ s/%26/&/g;
  731. return $html;
  732. }
  733. sub UrlEncode {
  734. my $str = shift;
  735. return '' unless $str;
  736. utf8::encode($str); # turn to byte string
  737. my @letters = split(//, $str);
  738. my %safe = map {$_ => 1} ('a' .. 'z', 'A' .. 'Z', '0' .. '9', '-', '_', '.', '!', '~', '*', "'", '(', ')', '#');
  739. foreach my $letter (@letters) {
  740. $letter = sprintf("%%%02x", ord($letter)) unless $safe{$letter};
  741. }
  742. return join('', @letters);
  743. }
  744. sub UrlDecode {
  745. my $str = shift;
  746. $str =~ s/%([0-9a-f][0-9a-f])/chr(hex($1))/eg;
  747. utf8::decode($str); # make internal string
  748. return $str;
  749. }
  750. sub QuoteRegexp {
  751. my $re = shift;
  752. $re =~ s/([\\\[\]\$()^.])/\\$1/g;
  753. return $re;
  754. }
  755. sub GetRaw {
  756. my $uri = shift;
  757. return unless eval { require LWP::UserAgent; };
  758. my $ua = LWP::UserAgent->new;
  759. my $response = $ua->get($uri);
  760. return $response->decoded_content if $response->is_success;
  761. }
  762. sub DoJournal {
  763. print GetHeader(undef, T('Journal'));
  764. print $q->start_div({-class=>'content journal'});
  765. PrintJournal(map { GetParam($_, ''); } qw(num num regexp mode offset search variation));
  766. print $q->end_div();
  767. PrintFooter();
  768. }
  769. sub JournalSort { $b cmp $a }
  770. sub PrintJournal {
  771. return if $CollectingJournal; # avoid infinite loops
  772. local $CollectingJournal = 1;
  773. my ($num, $numMore, $regexp, $mode, $offset, $search, $variation) = @_;
  774. $variation ||= 'journal';
  775. $regexp ||= '^\d\d\d\d-\d\d-\d\d';
  776. $num ||= 10;
  777. $numMore = $num unless $numMore ne '';
  778. $offset ||= 0;
  779. # FIXME: Should pass filtered list of pages to SearchTitleAndBody to save time?
  780. my @pages = sort JournalSort (grep(/$regexp/, $search ? SearchTitleAndBody($search) : AllPagesList()));
  781. @pages = reverse @pages if $mode eq 'reverse' or $mode eq 'future';
  782. $b = $Today // CalcDay($Now);
  783. if ($mode eq 'future' || $mode eq 'past') {
  784. my $compare = $mode eq 'future' ? -1 : 1;
  785. for (my $i = 0; $i < @pages; $i++) {
  786. $a = $pages[$i];
  787. if (JournalSort() == $compare) {
  788. @pages = @pages[$i .. $#pages];
  789. last;
  790. }
  791. }
  792. }
  793. return unless $pages[$offset];
  794. print $q->start_div({-class=>'journal'});
  795. my $next = $offset + PrintAllPages(1, 1, $num, $variation, @pages[$offset .. $#pages]);
  796. print $q->end_div();
  797. $regexp = UrlEncode($regexp);
  798. $search = UrlEncode($search);
  799. if ($pages[$next] and $numMore != 0) {
  800. print $q->p({-class=>'more'}, ScriptLink("action=more;num=$numMore;regexp=$regexp;search=$search;mode=$mode;offset=$next;variation=$variation", T('More...'), 'more'));
  801. }
  802. }
  803. sub PrintAllPages {
  804. my ($links, $comments, $num, $variation, @pages) = @_;
  805. my $lang = GetParam('lang', 0);
  806. my ($i, $n) = 0;
  807. for my $id (@pages) {
  808. last if $n >= $JournalLimit and not UserIsAdmin() or $num and $n >= $num;
  809. $i++; # pages looked at
  810. local ($OpenPageName, %Page); # this is local!
  811. OpenPage($id);
  812. my @languages = split(/,/, $Page{languages});
  813. next if $lang and @languages and not grep(/$lang/, @languages);
  814. next if PageMarkedForDeletion();
  815. next if substr($Page{text}, 0, 10) eq '#REDIRECT ';
  816. print $q->start_div({-class=>'page'}),
  817. $q->h1($links ? GetPageLink($id)
  818. : $q->a({-name=>$id}, UrlEncode(FreeToNormal($id))));
  819. if ($variation ne 'titles') {
  820. PrintPageHtml();
  821. PrintPageCommentsLink($id, $comments);
  822. }
  823. print $q->end_div();
  824. $n++; # pages actually printed
  825. }
  826. return $i;
  827. }
  828. sub PrintPageCommentsLink {
  829. my ($id, $comments) = @_;
  830. if ($comments and $CommentsPattern and $id !~ /$CommentsPattern/) {
  831. print $q->p({-class=>'comment'},
  832. GetPageLink($CommentsPrefix . $id, T('Comments on this page')));
  833. }
  834. }
  835. sub RSS {
  836. return if $CollectingJournal; # avoid infinite loops when using full=1
  837. local $CollectingJournal = 1;
  838. my $maxitems = shift;
  839. my @uris = @_;
  840. my %lines;
  841. if (not eval { require XML::RSS; }) {
  842. my $err = $@;
  843. return $q->div({-class=>'rss'}, $q->p({-class=>'error'}, $q->strong(T('XML::RSS is not available on this system.')), $err));
  844. }
  845. # All strings that are concatenated with strings returned by the RSS
  846. # feed must be decoded. Without this decoding, 'diff' and 'history'
  847. # translations will be double encoded when printing the result.
  848. my $tDiff = T('diff');
  849. my $tHistory = T('history');
  850. my $wikins = 'http://purl.org/rss/1.0/modules/wiki/';
  851. my $rdfns = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
  852. @uris = map { my $x = $_; $x =~ s/^"?(.*?)"?$/$1/; $x; } @uris; # strip quotes of uris
  853. my ($str, %data) = GetRss(@uris);
  854. foreach my $uri (keys %data) {
  855. my $data = $data{$uri};
  856. if (not $data) {
  857. $str .= $q->p({-class=>'error'}, $q->strong(Ts('%s returned no data, or LWP::UserAgent is not available.',
  858. $q->a({-href=>$uri}, $uri))));
  859. } else {
  860. my $rss = new XML::RSS;
  861. eval { local $SIG{__DIE__}; $rss->parse($data); };
  862. if ($@) {
  863. $str .= $q->p({-class=>'error'}, $q->strong(Ts('RSS parsing failed for %s', $q->a({-href=>$uri}, $uri)) . ': ' . $@));
  864. } else {
  865. my $interwiki;
  866. if (@uris > 1) {
  867. RssInterwikiTranslateInit(); # not needed anywhere else thus init only now and not in ReInit
  868. $interwiki = $rss->{channel}->{$wikins}->{interwiki};
  869. $interwiki =~ s/^\s+//; # when RDF is used, sometimes whitespace remains,
  870. $interwiki =~ s/\s+$//; # which breaks the test for an existing $interwiki below
  871. $interwiki ||= $rss->{channel}->{$rdfns}->{value};
  872. $interwiki = $RssInterwikiTranslate{$interwiki} if $RssInterwikiTranslate{$interwiki};
  873. $interwiki ||= $RssInterwikiTranslate{$uri};
  874. }
  875. my $num = 999;
  876. $str .= $q->p({-class=>'error'}, $q->strong(Ts('No items found in %s.', $q->a({-href=>$uri}, $uri))))
  877. unless @{$rss->{items}};
  878. foreach my $i (@{$rss->{items}}) {
  879. my $line;
  880. my $date = $i->{dc}->{date};
  881. if (not $date and $i->{pubDate}) {
  882. $date = $i->{pubDate};
  883. my %mon = (Jan=>1, Feb=>2, Mar=>3, Apr=>4, May=>5, Jun=>6,
  884. Jul=>7, Aug=>8, Sep=>9, Oct=>10, Nov=>11, Dec=>12);
  885. $date =~ s/^(?:[A-Z][a-z][a-z], )?(\d\d?) ([A-Z][a-z][a-z]) (\d\d(?:\d\d)?)/ # pubDate uses RFC 822
  886. sprintf('%04d-%02d-%02d', ($3 < 100 ? 1900 + $3 : $3), $mon{$2}, $1)/e;
  887. }
  888. $date ||= sprintf("%03d", $num--); # for RSS 0.91 feeds without date, descending
  889. my $title = $i->{title};
  890. my $description = $i->{description};
  891. if (not $title and $description) { # title may be missing in RSS 2.00
  892. $title = $description;
  893. $description = '';
  894. }
  895. $title = $i->{link} if not $title and $i->{link}; # if description and title are missing
  896. $line .= ' (' . $q->a({-href=>$i->{$wikins}->{diff}}, $tDiff) . ')' if $i->{$wikins}->{diff};
  897. $line .= ' (' . $q->a({-href=>$i->{$wikins}->{history}}, $tHistory) . ')' if $i->{$wikins}->{history};
  898. if ($title) {
  899. if ($i->{link}) {
  900. $line .= ' ' . $q->a({-href=>$i->{link}, -title=>$date},
  901. ($interwiki ? $interwiki . ':' : '') . $title);
  902. } else {
  903. $line .= ' ' . $title;
  904. }
  905. }
  906. my $contributor = $i->{dc}->{contributor};
  907. $contributor ||= $i->{$wikins}->{username};
  908. $contributor =~ s/^\s+//;
  909. $contributor =~ s/\s+$//;
  910. $contributor ||= $i->{$rdfns}->{value};
  911. $line .= $q->span({-class=>'contributor'}, $q->span(T(' . . . .') . ' ') . $contributor) if $contributor;
  912. if ($description) {
  913. if ($description =~ /</) {
  914. $line .= $q->div({-class=>'description'}, $description);
  915. } else {
  916. $line .= $q->span({class=>'dash'}, ' &#8211; ') . $q->strong({-class=>'description'}, $description);
  917. }
  918. }
  919. $date .= ' ' while ($lines{$date}); # make sure this is unique
  920. $lines{$date} = $line;
  921. }
  922. }
  923. }
  924. }
  925. my @lines = sort { $b cmp $a } keys %lines;
  926. @lines = @lines[0 .. $maxitems-1] if $maxitems and $#lines > $maxitems;
  927. my $date = '';
  928. foreach my $key (@lines) {
  929. my $line = $lines{$key};
  930. if ($key =~ /(\d\d\d\d(?:-\d?\d)?(?:-\d?\d)?)(?:[T ](\d?\d:\d\d))?/) {
  931. my ($day, $time) = ($1, $2);
  932. if ($day ne $date) {
  933. $str .= '</ul>' if $date; # close ul except for the first time where no open ul exists
  934. $date = $day;
  935. $str .= $q->p($q->strong($day)) . '<ul>';
  936. }
  937. $line = $q->span({-class=>'time'}, $time . ' UTC ') . $line if $time;
  938. } elsif (not $date) {
  939. $str .= '<ul>'; # if the feed doesn't have any dates we need to start the list anyhow
  940. $date = $Now; # to ensure the list starts only once
  941. }
  942. $str .= $q->li($line);
  943. }
  944. $str .= '</ul>' if $date;
  945. return $q->div({-class=>'rss'}, $str);
  946. }
  947. sub GetRss {
  948. my %todo = map {$_, GetRssFile($_)} @_;
  949. my %data = ();
  950. my $str = '';
  951. if (GetParam('cache', $UseCache) > 0) {
  952. foreach my $uri (keys %todo) { # read cached rss files if possible
  953. if ($Now - (stat($todo{$uri}))[9] < $RssCacheHours * 3600) {
  954. $data{$uri} = ReadFile($todo{$uri});
  955. delete($todo{$uri}); # no need to fetch them below
  956. }
  957. }
  958. }
  959. my @need_cache = keys %todo;
  960. if (keys %todo > 1) { # try parallel access if available
  961. eval { # see code example in LWP::Parallel, not LWP::Parallel::UserAgent (no callbacks here)
  962. require LWP::Parallel::UserAgent;
  963. my $pua = LWP::Parallel::UserAgent->new();
  964. foreach my $uri (keys %todo) {
  965. if (my $res = $pua->register(HTTP::Request->new('GET', $uri))) {
  966. $str .= $res->error_as_HTML;
  967. }
  968. }
  969. %todo = (); # because the uris in the response may have changed due to redirects
  970. my $entries = $pua->wait();
  971. foreach (keys %$entries) {
  972. my $uri = $entries->{$_}->request->uri;
  973. $data{$uri} = $entries->{$_}->response->decoded_content;
  974. }
  975. }
  976. }
  977. foreach my $uri (keys %todo) { # default operation: synchronous fetching
  978. $data{$uri} = GetRaw($uri);
  979. }
  980. if (GetParam('cache', $UseCache) > 0) {
  981. CreateDir($RssDir);
  982. foreach my $uri (@need_cache) {
  983. my $data = $data{$uri};
  984. # possibly a Latin-1 file without encoding attribute will cause a problem?
  985. $data =~ s/encoding="[^"]*"/encoding="UTF-8"/; # content was converted
  986. WriteStringToFile(GetRssFile($uri), $data) if $data;
  987. }
  988. }
  989. return $str, %data;
  990. }
  991. sub GetRssFile {
  992. return $RssDir . '/' . UrlEncode(shift);
  993. }
  994. sub RssInterwikiTranslateInit {
  995. return unless $RssInterwikiTranslate;
  996. %RssInterwikiTranslate = ();
  997. foreach (split(/\n/, GetPageContent($RssInterwikiTranslate))) {
  998. if (/^ ([^ ]+)[ \t]+([^ ]+)$/) {
  999. $RssInterwikiTranslate{$1} = $2;
  1000. }
  1001. }
  1002. }
  1003. sub GetInterSiteUrl {
  1004. my ($site, $page, $quote) = @_;
  1005. return unless $page;
  1006. $page = join('/', map { UrlEncode($_) } split(/\//, $page)) if $quote; # Foo:bar+baz is not quoted, [[Foo:bar baz]] is.
  1007. my $url = $InterSite{$site} or return;
  1008. $url =~ s/\%s/$page/g or $url .= $page;
  1009. return $url;
  1010. }
  1011. sub BracketLink { # brackets can be removed via CSS
  1012. return $q->span($q->span({class=>'bracket'}, '[') . (shift) . $q->span({class=>'bracket'}, ']'));
  1013. }
  1014. sub GetInterLink {
  1015. my ($id, $text, $bracket, $quote) = @_;
  1016. my ($site, $page) = split(/:/, $id, 2);
  1017. $page =~ s/&amp;/&/g; # Unquote common URL HTML
  1018. my $url = GetInterSiteUrl($site, $page, $quote);
  1019. my $class = 'inter ' . $site;
  1020. return "[$id $text]" if $text and $bracket and not $url;
  1021. return "[$id]" if $bracket and not $url;
  1022. return $id if not $url;
  1023. if ($bracket and not $text) {
  1024. $text = BracketLink(++$FootnoteNumber);
  1025. $class .= ' number';
  1026. } elsif (not $text) {
  1027. $text = $q->span({-class=>'site'}, $site)
  1028. . $q->span({-class=>'separator'}, ':')
  1029. . $q->span({-class=>'interpage'}, $page);
  1030. } elsif ($bracket) { # and $text is set
  1031. $class .= ' outside';
  1032. }
  1033. return $q->a({-href=>$url, -class=>$class}, $text);
  1034. }
  1035. sub InterInit {
  1036. %InterSite = ();
  1037. foreach (split(/\n/, GetPageContent($InterMap))) {
  1038. if (/^ ($InterSitePattern)[ \t]+([^ ]+)$/) {
  1039. $InterSite{$1} = $2;
  1040. }
  1041. }
  1042. }
  1043. sub GetUrl {
  1044. my ($url, $text, $bracket, $images) = @_;
  1045. $url =~ /^($UrlProtocols)/;
  1046. my $class = "url $1";
  1047. if ($NetworkFile && $url =~ m|^file:///| && !$AllNetworkFiles
  1048. or !$NetworkFile && $url =~ m|^file:|) {
  1049. # Only do remote file:// links. No file:///c|/windows.
  1050. return $url;
  1051. } elsif ($bracket and not defined $text) {
  1052. $text = BracketLink(++$FootnoteNumber);
  1053. $class .= ' number';
  1054. } elsif (not defined $text) {
  1055. $text = $url;
  1056. } elsif ($bracket) { # and $text is set
  1057. $class .= ' outside';
  1058. }
  1059. $url = UnquoteHtml($url); # links should be unquoted again
  1060. if ($images and $url =~ /^(http:|https:|ftp:).+\.$ImageExtensions$/i) {
  1061. return $q->img({-src=>$url, -alt=>$url, -class=>$class});
  1062. } else {
  1063. return $q->a({-href=>$url, -class=>$class}, $text);
  1064. }
  1065. }
  1066. sub GetPageOrEditLink { # use GetPageLink and GetEditLink if you know the result!
  1067. my ($id, $text, $bracket, $free) = @_;
  1068. $id = FreeToNormal($id);
  1069. my ($class, $resolved, $title, $exists) = ResolveId($id);
  1070. if (not $text and $resolved and $bracket) {
  1071. $text = BracketLink(++$FootnoteNumber);
  1072. $class .= ' number';
  1073. $title = NormalToFree($id);
  1074. }
  1075. my $link = $text || NormalToFree($id);
  1076. if ($resolved) { # anchors don't exist as pages, therefore do not use $exists
  1077. return ScriptLink(UrlEncode($resolved), $link, $class, undef, $title);
  1078. } else { # reproduce markup if $UseQuestionmark
  1079. return GetEditLink($id, UnquoteHtml($bracket ? "[$link]" : $link)) unless $UseQuestionmark;
  1080. $link = QuoteHtml($id) . GetEditLink($id, '?');
  1081. $link .= ($free ? '|' : ' ') . $text if $text and FreeToNormal($text) ne $id;
  1082. $link = "[[$link]]" if $free;
  1083. $link = "[$link]" if $bracket or not $free and $text;
  1084. return $link;
  1085. }
  1086. }
  1087. sub GetPageLink { # use if you want to force a link to local pages, whether it exists or not
  1088. my ($id, $name, $class, $accesskey) = @_;
  1089. $id = FreeToNormal($id);
  1090. $name ||= $id;
  1091. $class .= ' ' if $class;
  1092. return ScriptLink(UrlEncode($id), NormalToFree($name), $class . 'local',
  1093. undef, undef, $accesskey);
  1094. }
  1095. sub GetEditLink { # shortcut
  1096. my ($id, $name, $upload, $accesskey) = @_;
  1097. $id = FreeToNormal($id);
  1098. my $action = 'action=edit;id=' . UrlEncode($id);
  1099. $action .= ';upload=1' if $upload;
  1100. return ScriptLink($action, NormalToFree($name), 'edit', undef, T('Click to edit this page'), $accesskey);
  1101. }
  1102. sub ScriptUrl {
  1103. my $action = shift;
  1104. if ($action =~ /^($UrlProtocols)\%3a/ or $action =~ /^\%2f/) { # nearlinks and other URLs
  1105. $action =~ s/%([0-9a-f][0-9a-f])/chr(hex($1))/eg; # undo urlencode
  1106. # do nothing
  1107. } else {
  1108. $action = $ScriptName . (($UsePathInfo and index($action, '=') == -1) ? '/' : '?') . $action;
  1109. }
  1110. return $action unless wantarray;
  1111. return ($action, index($action, '=') != -1);
  1112. }
  1113. sub ScriptLink {
  1114. my ($action, $text, $class, $name, $title, $accesskey) = @_;
  1115. my ($url, $nofollow) = ScriptUrl($action);
  1116. my %params;
  1117. $params{-href} = $url;
  1118. $params{'-rel'} = 'nofollow' if $nofollow;
  1119. $params{'-class'} = $class if $class;
  1120. $params{'-name'} = $name if $name;
  1121. $params{'-title'} = $title if $title;
  1122. $params{'-accesskey'} = $accesskey if $accesskey;
  1123. return $q->a(\%params, $text);
  1124. }
  1125. sub GetDownloadLink {
  1126. my ($id, $image, $revision, $alt) = @_;
  1127. $alt ||= NormalToFree($id);
  1128. # if the page does not exist
  1129. return '[[' . ($image ? 'image' : 'download') . ':'
  1130. . ($UseQuestionmark ? QuoteHtml($id) . GetEditLink($id, '?', 1)
  1131. : GetEditLink($id, $id, 1)) . ']]'
  1132. unless $IndexHash{$id};
  1133. my $action;
  1134. if ($revision) {
  1135. $action = "action=download;id=" . UrlEncode($id) . ";revision=$revision";
  1136. } elsif ($UsePathInfo) {
  1137. $action = "download/" . UrlEncode($id);
  1138. } else {
  1139. $action = "action=download;id=" . UrlEncode($id);
  1140. }
  1141. if ($image) {
  1142. $action = $ScriptName . (($UsePathInfo and not $revision) ? '/' : '?') . $action;
  1143. return $action if $image == 2;
  1144. my $result = $q->img({-src=>$action, -alt=>UnquoteHtml($alt), -title=>UnquoteHtml($alt), -class=>'upload'});
  1145. $result = ScriptLink(UrlEncode($id), $result, 'image') unless $id eq $OpenPageName;
  1146. return $result;
  1147. } else {
  1148. return ScriptLink($action, $alt, 'upload');
  1149. }
  1150. }
  1151. sub PrintCache { # Use after OpenPage!
  1152. my @blocks = split($FS, $Page{blocks});
  1153. my @flags = split($FS, $Page{flags});
  1154. $FootnoteNumber = 0;
  1155. foreach my $block (@blocks) {
  1156. if (shift(@flags)) {
  1157. ApplyRules($block, 1, 1); # local links, anchors, current revision, no start tag
  1158. } else {
  1159. print $block;
  1160. }
  1161. }
  1162. }
  1163. sub PrintPageHtml { # print an open page
  1164. return unless GetParam('page', 1);
  1165. if ($Page{blocks} and defined $Page{flags} and GetParam('cache', $UseCache) > 0) {
  1166. PrintCache();
  1167. } else {
  1168. PrintWikiToHTML($Page{text}, 1); # save cache, current revision, no main lock
  1169. }
  1170. }
  1171. sub PrintPageDiff { # print diff for open page
  1172. my $diff = GetParam('diff', 0);
  1173. if ($UseDiff and $diff) {
  1174. PrintHtmlDiff($diff);
  1175. print $q->hr() if GetParam('page', 1);
  1176. }
  1177. }
  1178. sub ToString {
  1179. my ($sub_ref) = @_;
  1180. my $output;
  1181. open(my $outputFH, '>:encoding(UTF-8)', \$output) or die "Can't open memory file: $!";
  1182. my $oldFH = select $outputFH;
  1183. $sub_ref->();
  1184. select $oldFH;
  1185. close $outputFH;
  1186. my $output_fixed = $output; # do not delete!
  1187. utf8::decode($output_fixed); # this is a workarond for perl bug
  1188. return $output_fixed; # otherwise UTF8 characters are SOMETIMES not decoded.
  1189. }
  1190. sub PageHtml {
  1191. my ($id, $limit, $error) = @_;
  1192. OpenPage($id);
  1193. my $diff = ToString \&PrintPageDiff;
  1194. return $error if $limit and length($diff) > $limit;
  1195. my $page = ToString \&PrintPageHtml;
  1196. return $diff . $q->p($error) if $limit and length($diff . $page) > $limit;
  1197. return $diff . $page;
  1198. }
  1199. sub T {
  1200. my $text = shift;
  1201. return $Translate{$text} || $text;
  1202. }
  1203. sub Ts {
  1204. my ($text, $string) = @_;
  1205. $text = T($text);
  1206. $text =~ s/\%s/$string/ if defined($string);
  1207. return $text;
  1208. }
  1209. sub Tss {
  1210. my $text = $_[0];
  1211. $text = T($text);
  1212. $text =~ s/\%([1-9])/$_[$1]/eg;
  1213. return $text;
  1214. }
  1215. sub GetId {
  1216. my $id = UnquoteHtml(GetParam('id', GetParam('title', ''))); # id=x or title=x -> x
  1217. if (not $id) {
  1218. my @keywords = $q->keywords;
  1219. foreach my $keyword (@keywords) {
  1220. utf8::decode($keyword);
  1221. }
  1222. $id ||= join('_', @keywords); # script?p+q -> p_q
  1223. }
  1224. if ($UsePathInfo) {
  1225. my $path = $q->path_info;
  1226. utf8::decode($path);
  1227. my @path = split(/\//, $path);
  1228. $id ||= pop(@path); # script/p/q -> q
  1229. foreach my $p (@path) {
  1230. SetParam($p, 1); # script/p/q -> p=1
  1231. }
  1232. }
  1233. return $id;
  1234. }
  1235. sub DoBrowseRequest {
  1236. # We can use the error message as the HTTP error code
  1237. ReportError(Ts('CGI Internal error: %s', $q->cgi_error), $q->cgi_error) if $q->cgi_error;
  1238. print $q->header(-status=>'304 NOT MODIFIED') and return if PageFresh(); # return value is ignored
  1239. my $id = GetId();
  1240. my $action = lc(GetParam('action', '')); # script?action=foo;id=bar
  1241. $action = 'download' if GetParam('download', '') and not $action; # script/download/id
  1242. if ($Action{$action}) {
  1243. &{$Action{$action}}($id);
  1244. } elsif ($action and defined &MyActions) {
  1245. eval { local $SIG{__DIE__}; MyActions(); };
  1246. } elsif ($action) {
  1247. ReportError(Ts('Invalid action parameter %s', $action), '501 NOT IMPLEMENTED');
  1248. } elsif (GetParam('match', '') ne '') {
  1249. SetParam('action', 'index'); # make sure this gets a NOINDEX
  1250. DoIndex();
  1251. } elsif (GetParam('search', '') ne '') { # allow search for "0"
  1252. SetParam('action', 'search'); # make sure this gets a NOINDEX
  1253. DoSearch();
  1254. } elsif (GetParam('title', '') and not GetParam('Cancel', '')) {
  1255. DoPost(GetParam('title', ''));
  1256. } else {
  1257. BrowseResolvedPage($id || $HomePage); # default action!
  1258. }
  1259. }
  1260. sub ValidId { # hack alert: returns error message if invalid, and unfortunately the empty string if valid!
  1261. my $id = FreeToNormal(shift);
  1262. return T('Page name is missing') unless $id;
  1263. require bytes;
  1264. return Ts('Page name is too long: %s', $id) if bytes::length($id) > $PageNameLimit;
  1265. return Ts('Invalid Page %s (must not end with .db)', $id) if $id =~ m|\.db$|;
  1266. return Ts('Invalid Page %s (must not end with .lck)', $id) if $id =~ m|\.lck$|;
  1267. return Ts('Invalid Page %s', $id) if $FreeLinks ? $id !~ m|^$FreeLinkPattern$| : $id !~ m|^$LinkPattern$|;
  1268. }
  1269. sub ValidIdOrDie {
  1270. my $id = shift;
  1271. my $error = ValidId($id);
  1272. ReportError($error, '400 BAD REQUEST') if $error;
  1273. return 1;
  1274. }
  1275. sub ResolveId { # return css class, resolved id, title (eg. for popups), exist-or-not
  1276. my $id = shift;
  1277. return ('local', $id, '', 1) if $IndexHash{$id};
  1278. return ('', '', '', '');
  1279. }
  1280. sub BrowseResolvedPage {
  1281. my $id = FreeToNormal(shift);
  1282. my ($class, $resolved, $title, $exists) = ResolveId($id);
  1283. if ($class and $class eq 'near' and not GetParam('rcclusteronly', 0)) { # nearlink (is url)
  1284. print $q->redirect({-uri=>$resolved});
  1285. } elsif ($class and $class eq 'alias') { # an anchor was found instead of a page
  1286. ReBrowsePage($resolved);
  1287. } elsif (not $resolved and $NotFoundPg and $id !~ /$CommentsPattern/) { # custom page-not-found message
  1288. BrowsePage($NotFoundPg);
  1289. } elsif ($resolved) { # an existing page was found
  1290. BrowsePage($resolved, GetParam('raw', 0));
  1291. } else { # new page!
  1292. BrowsePage($id, GetParam('raw', 0), undef, '404 NOT FOUND') if ValidIdOrDie($id);
  1293. }
  1294. }
  1295. sub NewText { # only if no revision is available
  1296. my $id = shift;
  1297. if ($CommentsPrefix and $id =~ /^($CommentsPrefix)/) {
  1298. return T('There are no comments, yet. Be the first to leave a comment!');
  1299. } elsif ($id eq $HomePage) {
  1300. return T('Welcome!');
  1301. } else {
  1302. return Ts('This page does not exist, but you can %s.',
  1303. '[' . ScriptUrl('action=edit;id=' . UrlEncode($id)) . ' '
  1304. . T('create it now') . ']');
  1305. }
  1306. }
  1307. sub BrowsePage {
  1308. my ($id, $raw, $comment, $status) = @_;
  1309. OpenPage($id);
  1310. my ($revisionPage, $revision) = GetTextRevision(GetParam('revision', ''));
  1311. my $text = $revisionPage->{text};
  1312. $text = NewText($id) unless $revision or $Page{revision} or $comment; # new text for new pages
  1313. # handle a single-level redirect
  1314. my $oldId = GetParam('oldid', '');
  1315. if ((substr($text, 0, 10) eq '#REDIRECT ')) {
  1316. if ($oldId) {
  1317. $Message .= $q->p(T('Too many redirections'));
  1318. } elsif ($revision) {
  1319. $Message .= $q->p(T('No redirection for old revisions'));
  1320. } elsif (($FreeLinks and $text =~ /^\#REDIRECT\s+\[\[$FreeLinkPattern\]\]/)
  1321. or ($WikiLinks and $text =~ /^\#REDIRECT\s+$LinkPattern/)) {
  1322. return ReBrowsePage(FreeToNormal($1), $id);
  1323. } else {
  1324. $Message .= $q->p(T('Invalid link pattern for #REDIRECT'));
  1325. }
  1326. }
  1327. # shortcut if we only need the raw text: no caching, no diffs, no html.
  1328. if ($raw) {
  1329. print GetHttpHeader('text/plain', $Page{ts}, $IndexHash{$id} ? undef : '404 NOT FOUND');
  1330. print $Page{ts} . " # Do not delete this line when editing!\n" if $raw == 2;
  1331. print $text;
  1332. return;
  1333. }
  1334. # normal page view
  1335. my $msg = GetParam('msg', '');
  1336. $Message .= $q->p($msg) if $msg; # show message if the page is shown
  1337. SetParam('msg', '');
  1338. print GetHeader($id, NormalToFree($id), $oldId, undef, $status);
  1339. my $showDiff = GetParam('diff', 0);
  1340. if ($UseDiff and $showDiff) {
  1341. PrintHtmlDiff($showDiff, GetParam('diffrevision'), $revisionPage, $Page{revision});
  1342. print $q->hr();
  1343. }
  1344. PrintPageContent($text, $revision, $comment);
  1345. SetParam('rcclusteronly', $id) if FreeToNormal(GetCluster($text)) eq $id; # automatically filter by cluster
  1346. PrintRcHtml($id);
  1347. PrintFooter($id, $revision, $comment, $revisionPage);
  1348. }
  1349. sub ReBrowsePage {
  1350. my ($id, $oldId) = map { UrlEncode($_); } @_; # encode before printing URL
  1351. if ($oldId) { # Target of #REDIRECT (loop breaking)
  1352. print GetRedirectPage("action=browse;oldid=$oldId;id=$id", $id);
  1353. } else {
  1354. print GetRedirectPage($id, $id);
  1355. }
  1356. }
  1357. sub GetRedirectPage {
  1358. my ($action, $name) = @_;
  1359. my ($url, $html);
  1360. if (GetParam('raw', 0)) {
  1361. $html = GetHttpHeader('text/plain');
  1362. $html .= Ts('Please go on to %s.', $action); # no redirect
  1363. return $html;
  1364. }
  1365. $url = $ScriptName . (($UsePathInfo and $action !~ /=/) ? '/' : '?') . $action;
  1366. my $nameLink = $q->a({-href=>$url}, $name);
  1367. my %headers = (-uri=>$url);
  1368. my $cookie = Cookie();
  1369. $headers{-cookie} = $cookie if $cookie;
  1370. return $q->redirect(%headers);
  1371. }
  1372. sub DoRandom {
  1373. my @pages = AllPagesList();
  1374. ReBrowsePage($pages[int(rand($#pages + 1))]);
  1375. }
  1376. sub PageFresh { # pages can depend on other pages (ie. last update), admin status, and css
  1377. return 1 if $q->http('HTTP_IF_NONE_MATCH') and GetParam('cache', $UseCache) >= 2
  1378. and $q->http('HTTP_IF_NONE_MATCH') eq PageEtag();
  1379. }
  1380. sub PageEtag {
  1381. my ($changed, %params) = CookieData();
  1382. return UrlEncode(join($FS, $LastUpdate||$Now, sort(values %params))); # no CTL in field values
  1383. }
  1384. sub FileFresh { # old files are never stale, current files are stale when the page was modified
  1385. return 1 if $q->http('HTTP_IF_NONE_MATCH') and GetParam('cache', $UseCache) >= 2
  1386. and (GetParam('revision', 0) or $q->http('HTTP_IF_NONE_MATCH') eq $Page{ts});
  1387. }
  1388. sub BrowseRc {
  1389. my $id = shift;
  1390. if (GetParam('raw', 0)) {
  1391. print GetHttpHeader('text/plain');
  1392. PrintRcText();
  1393. } else {
  1394. PrintRcHtml($id || $RCName, 1);
  1395. }
  1396. }
  1397. sub GetRcLines { # starttime, hash of seen pages to use as a second return value
  1398. my $starttime = shift || GetParam('from', 0) ||
  1399. $Now - GetParam('days', $RcDefault) * 86400; # 24*60*60
  1400. my $filterOnly = GetParam('rcfilteronly', '');
  1401. # these variables apply accross logfiles
  1402. my %match = $filterOnly ? map { $_ => 1 } SearchTitleAndBody($filterOnly) : ();
  1403. my %following = ();
  1404. my @result = ();
  1405. my $ts;
  1406. # check the first timestamp in the default file, maybe read old log file
  1407. if (open(my $F, '<:encoding(UTF-8)', $RcFile)) {
  1408. my $line = <$F>;
  1409. ($ts) = split(/$FS/, $line); # the first timestamp in the regular rc file
  1410. }
  1411. if (not $ts or $ts > $starttime) { # we need to read the old rc file, too
  1412. push(@result, GetRcLinesFor($RcOldFile, $starttime, \%match, \%following));
  1413. }
  1414. push(@result, GetRcLinesFor($RcFile, $starttime, \%match, \%following));
  1415. # GetRcLinesFor is trying to save memory space, but some operations
  1416. # can only happen once we have all the data.
  1417. return LatestChanges(StripRollbacks(@result));
  1418. }
  1419. sub LatestChanges {
  1420. my $all = GetParam('all', $ShowAll);
  1421. my @result = @_;
  1422. my %seen = ();
  1423. for (my $i = $#result; $i >= 0; $i--) {
  1424. my $id = $result[$i][1];
  1425. if ($all) {
  1426. $result[$i][9] = 1 unless $seen{$id}; # mark latest edit
  1427. } else {
  1428. splice(@result, $i, 1) if $seen{$id}; # remove older edits
  1429. }
  1430. $seen{$id} = 1;
  1431. }
  1432. my $to = GetParam('upto', 0);
  1433. if ($to) {
  1434. for (my $i = 0; $i < $#result; $i++) {
  1435. if ($result[$i][0] > $to) {
  1436. splice(@result, $i);
  1437. last;
  1438. }
  1439. }
  1440. }
  1441. return reverse @result;
  1442. }
  1443. sub StripRollbacks {
  1444. my @result = @_;
  1445. if (not (GetParam('all', $ShowAll) or GetParam('rollback', $ShowRollbacks))) { # strip rollbacks
  1446. my (%rollback);
  1447. for (my $i = $#result; $i >= 0; $i--) {
  1448. # some fields have a different meaning if looking at rollbacks
  1449. my ($ts, $id, $target_ts, $target_id) = @{$result[$i]};
  1450. if ($id eq '[[rollback]]') {
  1451. if ($target_id) {
  1452. $rollback{$target_id} = $target_ts; # single page rollback
  1453. splice(@result, $i, 1); # strip marker
  1454. } else {
  1455. my $end = $i;
  1456. while ($ts > $target_ts and $i > 0) {
  1457. $i--; # quickly skip all these lines
  1458. $ts = $result[$i][0];
  1459. }
  1460. splice(@result, $i + 1, $end - $i);
  1461. $i++; # compensate $i-- in for loop
  1462. }
  1463. } elsif ($rollback{$id} and $ts > $rollback{$id}) {
  1464. splice(@result, $i, 1); # strip rolled back single pages
  1465. }
  1466. }
  1467. } else { # just strip the marker left by DoRollback()
  1468. for (my $i = $#result; $i >= 0; $i--) {
  1469. splice(@result, $i, 1) if $result[$i][1] eq '[[rollback]]'; # id
  1470. }
  1471. }
  1472. return @result;
  1473. }
  1474. sub GetRcLinesFor {
  1475. my $file = shift;
  1476. my $starttime = shift;
  1477. my %match = %{$_[0]}; # deref
  1478. my %following = %{$_[1]}; # deref
  1479. # parameters
  1480. my $showminoredit = GetParam('showedit', $ShowEdits); # show minor edits
  1481. my $all = GetParam('all', $ShowAll);
  1482. my ($idOnly, $userOnly, $hostOnly, $clusterOnly, $filterOnly, $match, $lang,
  1483. $followup) = map { UnquoteHtml(GetParam($_, '')); }
  1484. qw(rcidonly rcuseronly rchostonly
  1485. rcclusteronly rcfilteronly match lang followup);
  1486. # parsing and filtering
  1487. my @result = ();
  1488. open(my $F, '<:encoding(UTF-8)', $file) or return ();
  1489. while (my $line = <$F>) {
  1490. chomp($line);
  1491. my ($ts, $id, $minor, $summary, $host, $username, $revision,
  1492. $languages, $cluster) = split(/$FS/, $line);
  1493. next if $ts < $starttime;
  1494. $following{$id} = $ts if $followup and $followup eq $username;
  1495. next if $followup and (not $following{$id} or $ts <= $following{$id});
  1496. next if $idOnly and $idOnly ne $id;
  1497. next if $filterOnly and not $match{$id};
  1498. next if ($userOnly and $userOnly ne $username);
  1499. next if $minor == 1 and not $showminoredit; # skip minor edits (if [[rollback]] this is bogus)
  1500. next if not $minor and $showminoredit == 2; # skip major edits
  1501. next if $match and $id !~ /$match/i;
  1502. next if $hostOnly and $host !~ /$hostOnly/i;
  1503. my @languages = split(/,/, $languages);
  1504. next if $lang and @languages and not grep(/$lang/, @languages);
  1505. if ($PageCluster) {
  1506. ($cluster, $summary) = ($1, $2) if $summary =~ /^\[\[$FreeLinkPattern\]\] ?: *(.*)/
  1507. or $summary =~ /^$LinkPattern ?: *(.*)/;
  1508. next if ($clusterOnly and $clusterOnly ne $cluster);
  1509. $cluster = '' if $clusterOnly; # don't show cluster if $clusterOnly eq $cluster
  1510. if ($all < 2 and not $clusterOnly and $cluster) {
  1511. $summary = "$id: $summary"; # print the cluster instead of the page
  1512. $id = $cluster;
  1513. $revision = '';
  1514. }
  1515. } else {
  1516. $cluster = '';
  1517. }
  1518. $following{$id} = $ts if $followup and $followup eq $username;
  1519. push(@result, [$ts, $id, $minor, $summary, $host, $username, $revision,
  1520. \@languages, $cluster]);
  1521. }
  1522. return @result;
  1523. }
  1524. sub ProcessRcLines {
  1525. my ($printDailyTear, $printRCLine) = @_; # code references
  1526. # needed for output
  1527. my $date = '';
  1528. for my $line (GetRcLines()) {
  1529. my ($ts, $id, $minor, $summary, $host, $username, $revision, $languageref,
  1530. $cluster, $last) = @$line;
  1531. if ($date ne CalcDay($ts)) {
  1532. $date = CalcDay($ts);
  1533. $printDailyTear->($date);
  1534. }
  1535. $printRCLine->($id, $ts, $host, $username, $summary, $minor, $revision,
  1536. $languageref, $cluster, $last);
  1537. }
  1538. }
  1539. sub RcHeader {
  1540. my ($from, $upto, $html) = (GetParam('from', 0), GetParam('upto', 0), '');
  1541. my $days = GetParam('days') + 0 || $RcDefault; # force numeric $days
  1542. my $all = GetParam('all', $ShowAll);
  1543. my $edits = GetParam('showedit', $ShowEdits);
  1544. my $rollback = GetParam('rollback', $ShowRollbacks);
  1545. if ($from) {
  1546. $html .= $q->h2(Ts('Updates since %s', TimeToText(GetParam('from', 0))) . ' '
  1547. . ($upto ? Ts('up to %s', TimeToText($upto)) : ''));
  1548. } else {
  1549. $html .= $q->h2((GetParam('days', $RcDefault) != 1)
  1550. ? Ts('Updates in the last %s days', $days)
  1551. : Ts('Updates in the last day'));
  1552. }
  1553. my $action = '';
  1554. my ($idOnly, $userOnly, $hostOnly, $clusterOnly, $filterOnly,
  1555. $match, $lang, $followup) =
  1556. map {
  1557. my $val = GetParam($_, '');
  1558. $html .= $q->p($q->b('(' . Ts('for %s only', $val) . ')')) if $val;
  1559. $action .= ";$_=$val" if $val; # remember these parameters later!
  1560. $val;
  1561. } qw(rcidonly rcuseronly rchostonly rcclusteronly rcfilteronly
  1562. match lang followup);
  1563. my $rss = "action=rss$action;days=$days;all=$all;showedit=$edits";
  1564. if ($clusterOnly) {
  1565. $action = GetPageParameters('browse', $clusterOnly) . $action;
  1566. } else {
  1567. $action = "action=rc$action";
  1568. }
  1569. my @menu;
  1570. if ($all) {
  1571. push(@menu, ScriptLink("$action;days=$days;all=0;showedit=$edits",
  1572. T('List latest change per page only')));
  1573. } else {
  1574. push(@menu, ScriptLink("$action;days=$days;all=1;showedit=$edits",
  1575. T('List all changes')));
  1576. if ($rollback) {
  1577. push(@menu, ScriptLink("$action;days=$days;all=0;rollback=0;"
  1578. . "showedit=$edits", T('Skip rollbacks')));
  1579. } else {
  1580. push(@menu, ScriptLink("$action;days=$days;all=0;rollback=1;"
  1581. . "showedit=$edits", T('Include rollbacks')));
  1582. }
  1583. }
  1584. if ($edits) {
  1585. push(@menu, ScriptLink("$action;days=$days;all=$all;showedit=0",
  1586. T('List only major changes')));
  1587. } else {
  1588. push(@menu, ScriptLink("$action;days=$days;all=$all;showedit=1",
  1589. T('Include minor changes')));
  1590. }
  1591. return $html .
  1592. $q->p(join(' | ', (map { ScriptLink("$action;days=$_;all=$all;showedit=$edits", $_); } @RcDays)),
  1593. T('days'), $q->br(), @menu, $q->br(),
  1594. ScriptLink($action . ';from=' . ($LastUpdate + 1)
  1595. . ";all=$all;showedit=$edits", T('List later changes')),
  1596. ScriptLink($rss, T('RSS'), 'rss nopages nodiff'),
  1597. ScriptLink("$rss;full=1", T('RSS with pages'), 'rss pages nodiff'),
  1598. ScriptLink("$rss;full=1;diff=1", T('RSS with pages and diff'),
  1599. 'rss pages diff'));
  1600. }
  1601. sub GetScriptUrlWithRcParameters {
  1602. my $url = "$ScriptName?action=rss";
  1603. foreach my $param (qw(from upto days all showedit rollback rcidonly rcuseronly
  1604. rchostonly rcclusteronly rcfilteronly match lang
  1605. followup page diff full)) {
  1606. my $val = GetParam($param, undef);
  1607. $url .= ";$param=$val" if defined $val;
  1608. }
  1609. return $url;
  1610. }
  1611. sub GetFilterForm {
  1612. my $form = $q->strong(T('Filters'));
  1613. $form .= $q->input({-type=>'hidden', -name=>'action', -value=>'rc'});
  1614. $form .= $q->input({-type=>'hidden', -name=>'all', -value=>1}) if (GetParam('all', $ShowAll));
  1615. $form .= $q->input({-type=>'hidden', -name=>'showedit', -value=>1}) if (GetParam('showedit', $ShowEdits));
  1616. if (GetParam('days', $RcDefault) != $RcDefault) {
  1617. $form .= $q->input({-type=>'hidden', -name=>'days', -value=>GetParam('days', $RcDefault)});
  1618. }
  1619. my $table = '';
  1620. foreach my $h (['match' => T('Title:')],
  1621. ['rcfilteronly' => T('Title and Body:')],
  1622. ['rcuseronly' => T('Username:')], ['rchostonly' => T('Host:')],
  1623. ['followup' => T('Follow up to:')]) {
  1624. $table .= $q->Tr($q->td($q->label({-for=>$h->[0]}, $h->[1])),
  1625. $q->td($q->textfield(-name=>$h->[0], -id=>$h->[0], -size=>20)));
  1626. }
  1627. if (%Languages) {
  1628. $table .= $q->Tr($q->td($q->label({-for=>'rclang'}, T('Language:')))
  1629. . $q->td($q->textfield(-name=>'lang', -id=>'rclang', -size=>10,
  1630. -default=>GetParam('lang', ''))));
  1631. }
  1632. return GetFormStart(undef, 'get', 'filter') . $q->p($form) . $q->table($table)
  1633. . $q->p($q->submit('dofilter', T('Go!'))) . $q->end_form;
  1634. }
  1635. sub RcHtml {
  1636. my ($html, $inlist) = ('', 0);
  1637. # Optimize param fetches and translations out of main loop
  1638. my $all = GetParam('all', $ShowAll);
  1639. my $admin = UserIsAdmin();
  1640. my $rollback_was_possible = 0;
  1641. my $printDailyTear = sub {
  1642. my $date = shift;
  1643. if ($inlist) {
  1644. $html .= '</ul>';
  1645. $inlist = 0;
  1646. }
  1647. $html .= $q->p($q->strong($date));
  1648. if (not $inlist) {
  1649. $html .= '<ul>';
  1650. $inlist = 1;
  1651. }
  1652. };
  1653. my $printRCLine = sub {
  1654. my($id, $ts, $host, $username, $summary, $minor, $revision,
  1655. $languages, $cluster, $last) = @_;
  1656. my $all_revision = $last ? undef : $revision; # no revision for the last one
  1657. $host = QuoteHtml($host);
  1658. my $author = GetAuthorLink($host, $username);
  1659. my $sum = $summary ? $q->span({class=>'dash'}, ' &#8211; ')
  1660. . $q->strong(QuoteHtml($summary)) : '';
  1661. my $edit = $minor ? $q->em({class=>'type'}, T('(minor)')) : '';
  1662. my $lang = @{$languages}
  1663. ? $q->span({class=>'lang'}, '[' . join(', ', @{$languages}) . ']') : '';
  1664. my ($pagelink, $history, $diff, $rollback) = ('', '', '', '');
  1665. if ($all) {
  1666. $pagelink = GetOldPageLink('browse', $id, $all_revision, $id, $cluster);
  1667. my $rollback_is_possible = RollbackPossible($ts);
  1668. if ($admin and ($rollback_is_possible or $rollback_was_possible)) {
  1669. $rollback = $q->submit("rollback-$ts", T('rollback'));
  1670. $rollback_was_possible = $rollback_is_possible;
  1671. } else {
  1672. $rollback_was_possible = 0;
  1673. }
  1674. } elsif ($cluster) {
  1675. $pagelink = GetOldPageLink('browse', $id, $revision, $id, $cluster);
  1676. } else {
  1677. $pagelink = GetPageLink($id, $cluster);
  1678. $history = '(' . GetHistoryLink($id, T('history')) . ')';
  1679. }
  1680. if ($cluster and $PageCluster) {
  1681. $diff .= GetPageLink($PageCluster) . ':';
  1682. } elsif ($UseDiff and GetParam('diffrclink', 1)) {
  1683. if ($revision == 1) {
  1684. $diff .= '(' . $q->span({-class=>'new'}, T('new')) . ')';
  1685. } elsif ($all) {
  1686. $diff .= '(' . ScriptLinkDiff(2, $id, T('diff'), $all_revision) .')';
  1687. } else {
  1688. $diff .= '(' . ScriptLinkDiff($minor ? 2 : 1, $id, T('diff')) . ')';
  1689. }
  1690. }
  1691. $html .= $q->li($q->span({-class=>'time'}, CalcTime($ts)), $diff, $history,
  1692. $rollback, $pagelink, T(' . . . .'), $author, $sum, $lang,
  1693. $edit);
  1694. };
  1695. ProcessRcLines($printDailyTear, $printRCLine);
  1696. $html .= '</ul>' if $inlist;
  1697. # use delta between from and upto, or use days, whichever is available
  1698. my $to = GetParam('from', GetParam('upto', $Now - GetParam('days', $RcDefault) * 86400));
  1699. my $from = $to - (GetParam('upto') ? GetParam('upto') - GetParam('from') : GetParam('days', $RcDefault) * 86400);
  1700. my $more = "action=rc;from=$from;upto=$to";
  1701. foreach (qw(all showedit rollback rcidonly rcuseronly rchostonly
  1702. rcclusteronly rcfilteronly match lang followup)) {
  1703. my $val = GetParam($_, '');
  1704. $more .= ";$_=$val" if $val;
  1705. }
  1706. $html .= $q->p({-class=>'more'}, ScriptLink($more, T('More...'), 'more'));
  1707. return GetFormStart(undef, 'get', 'rc') . $html . $q->end_form;
  1708. }
  1709. sub PrintRcHtml { # to append RC to existing page, or action=rc directly
  1710. my ($id, $standalone) = @_;
  1711. my $rc = ($id eq $RCName or $id eq T($RCName) or T($id) eq $RCName);
  1712. if ($standalone) {
  1713. print GetHeader('', $rc ? NormalToFree($id) : Ts('All changes for %s', NormalToFree($id)));
  1714. }
  1715. if ($standalone or $rc or GetParam('rcclusteronly', '')) {
  1716. print $q->start_div({-class=>'rc'});
  1717. print $q->hr() unless $standalone or GetParam('embed', $EmbedWiki);
  1718. print RcHeader() . RcHtml() . GetFilterForm() . $q->end_div();
  1719. }
  1720. PrintFooter($id) if $standalone;
  1721. }
  1722. sub RcTextItem {
  1723. my ($name, $value) = @_;
  1724. $value = UnquoteHtml($value);
  1725. $value =~ s/\n+$//;
  1726. $value =~ s/\n+/\n /;
  1727. return $value ? $name . ': ' . $value . "\n" : '';
  1728. }
  1729. sub RcTextRevision {
  1730. my($id, $ts, $host, $username, $summary, $minor, $revision,
  1731. $languages, $cluster, $last) = @_;
  1732. my $link = $ScriptName
  1733. . (GetParam('all', $ShowAll) && ! $last
  1734. ? '?' . GetPageParameters('browse', $id, $revision, $cluster, $last)
  1735. : ($UsePathInfo ? '/' : '?') . UrlEncode($id));
  1736. print "\n", RcTextItem('title', NormalToFree($id)),
  1737. RcTextItem('description', $summary),
  1738. RcTextItem('generator', GetAuthor($host, $username)),
  1739. RcTextItem('language', join(', ', @{$languages})), RcTextItem('link', $link),
  1740. RcTextItem('last-modified', TimeToW3($ts)),
  1741. RcTextItem('revision', $revision),
  1742. RcTextItem('minor', $minor);
  1743. }
  1744. sub PrintRcText { # print text rss header and call ProcessRcLines
  1745. local $RecentLink = 0;
  1746. print RcTextItem('title', $SiteName),
  1747. RcTextItem('description', $SiteDescription), RcTextItem('link', $ScriptName),
  1748. RcTextItem('generator', 'Oddmuse'), RcTextItem('rights', $RssRights);
  1749. ProcessRcLines(sub {}, \&RcTextRevision);
  1750. }
  1751. sub GetRcRss {
  1752. my $date = TimeToRFC822($LastUpdate);
  1753. my %excluded = ();
  1754. if (GetParam("exclude", 1)) {
  1755. foreach (split(/\n/, GetPageContent($RssExclude))) {
  1756. if (/^ ([^ ]+)[ \t]*$/) { # only read lines with one word after one space
  1757. $excluded{$1} = 1;
  1758. }
  1759. }
  1760. }
  1761. my $rss = qq{<?xml version="1.0" encoding="UTF-8"?>\n};
  1762. if ($RssStyleSheet =~ /\.(xslt?|xml)$/) {
  1763. $rss .= qq{<?xml-stylesheet type="text/xml" href="$RssStyleSheet" ?>\n};
  1764. } elsif ($RssStyleSheet) {
  1765. $rss .= qq{<?xml-stylesheet type="text/css" href="$RssStyleSheet" ?>\n};
  1766. }
  1767. $rss .= qq{<rss version="2.0"
  1768. xmlns:wiki="http://purl.org/rss/1.0/modules/wiki/"
  1769. xmlns:dc="http://purl.org/dc/elements/1.1/"
  1770. xmlns:cc="http://web.resource.org/cc/"
  1771. xmlns:atom="http://www.w3.org/2005/Atom">
  1772. <channel>
  1773. <docs>http://blogs.law.harvard.edu/tech/rss</docs>
  1774. };
  1775. my $title = QuoteHtml($SiteName) . ': ' . GetParam('title', QuoteHtml(NormalToFree($HomePage)));
  1776. $rss .= "<title>$title</title>\n";
  1777. $rss .= "<link>" . ScriptUrl($HomePage) . "</link>\n";
  1778. $rss .= qq{<atom:link href="} . GetScriptUrlWithRcParameters()
  1779. . qq{" rel="self" type="application/rss+xml" />\n};
  1780. if ($SiteDescription) {
  1781. $rss .= "<description>" . QuoteHtml($SiteDescription) . "</description>\n"
  1782. }
  1783. $rss .= "<pubDate>$date</pubDate>\n";
  1784. $rss .= "<lastBuildDate>$date</lastBuildDate>\n";
  1785. $rss .= "<generator>Oddmuse</generator>\n";
  1786. $rss .= "<copyright>$RssRights</copyright>\n" if $RssRights;
  1787. if ($RssLicense) {
  1788. $rss .= join('', map {"<cc:license>" . QuoteHtml($_) . "</cc:license>\n"}
  1789. (ref $RssLicense eq 'ARRAY' ? @$RssLicense : $RssLicense))
  1790. }
  1791. $rss .= "<wiki:interwiki>$InterWikiMoniker</wiki:interwiki>\n" if $InterWikiMoniker;
  1792. if ($RssImageUrl) {
  1793. $rss .= "<image>\n";
  1794. $rss .= "<url>$RssImageUrl</url>\n";
  1795. $rss .= "<title>$title</title>\n"; # the same as the channel
  1796. $rss .= "<link>$ScriptName</link>\n"; # the same as the channel
  1797. $rss .= "</image>\n";
  1798. }
  1799. my $limit = GetParam("rsslimit", 15); # Only take the first 15 entries
  1800. my $count = 0;
  1801. ProcessRcLines(sub {}, sub {
  1802. my $id = shift;
  1803. return if $excluded{$id} or ($limit ne 'all' and $count++ >= $limit);
  1804. $rss .= "\n" . RssItem($id, @_);
  1805. });
  1806. $rss .= "</channel>\n</rss>\n";
  1807. return $rss;
  1808. }
  1809. sub RssItem {
  1810. my ($id, $ts, $host, $username, $summary, $minor, $revision,
  1811. $languages, $cluster, $last) = @_;
  1812. my $name = ItemName($id);
  1813. if (GetParam('full', 0)) { # full page means summary is not shown
  1814. $summary = PageHtml($id, 50 * 1024, T('This page is too big to send over RSS.'));
  1815. } else {
  1816. $summary = QuoteHtml($summary); # page summary must be quoted
  1817. }
  1818. my $date = TimeToRFC822($ts);
  1819. $username = QuoteHtml($username);
  1820. $username ||= $host;
  1821. my $rss = "<item>\n";
  1822. $rss .= "<title>$name</title>\n";
  1823. my $link = ScriptUrl(GetParam('all', $cluster)
  1824. ? GetPageParameters('browse', $id, $revision, $cluster, $last)
  1825. : UrlEncode($id));
  1826. $rss .= "<link>$link</link>\n<guid>$link</guid>\n";
  1827. $rss .= "<description>" . QuoteHtml($summary) . "</description>\n" if $summary;
  1828. $rss .= "<pubDate>" . $date . "</pubDate>\n";
  1829. $rss .= "<comments>" . ScriptUrl($CommentsPrefix . UrlEncode($id))
  1830. . "</comments>\n" if $CommentsPattern and $id !~ /$CommentsPattern/;
  1831. $rss .= "<dc:contributor>" . $username . "</dc:contributor>\n" if $username;
  1832. $rss .= "<wiki:status>" . (1 == $revision ? 'new' : 'updated') . "</wiki:status>\n";
  1833. $rss .= "<wiki:importance>" . ($minor ? 'minor' : 'major') . "</wiki:importance>\n";
  1834. $rss .= "<wiki:version>" . $revision . "</wiki:version>\n";
  1835. $rss .= "<wiki:history>" . ScriptUrl("action=history;id=" . UrlEncode($id))
  1836. . "</wiki:history>\n";
  1837. $rss .= "<wiki:diff>" . ScriptUrl("action=browse;diff=1;id=" . UrlEncode($id))
  1838. . "</wiki:diff>\n" if $UseDiff and GetParam('diffrclink', 1);
  1839. return $rss . "</item>\n";
  1840. }
  1841. sub DoRss {
  1842. print GetHttpHeader('application/xml');
  1843. print GetRcRss();
  1844. }
  1845. sub DoHistory {
  1846. my $id = shift;
  1847. ValidIdOrDie($id);
  1848. OpenPage($id);
  1849. if (GetParam('raw', 0)) {
  1850. DoRawHistory($id);
  1851. } else {
  1852. DoHtmlHistory($id);
  1853. }
  1854. }
  1855. sub DoRawHistory {
  1856. my ($id) = @_;
  1857. print GetHttpHeader('text/plain'),
  1858. RcTextItem('title', Ts('History of %s', NormalToFree($OpenPageName))),
  1859. RcTextItem('date', TimeToText($Now)),
  1860. RcTextItem('link', ScriptUrl("action=history;id=$OpenPageName;raw=1")),
  1861. RcTextItem('generator', 'Oddmuse');
  1862. SetParam('all', 1);
  1863. my @languages = split(/,/, $Page{languages});
  1864. RcTextRevision($id, $Page{ts}, $Page{host}, $Page{username}, $Page{summary},
  1865. $Page{minor}, $Page{revision}, \@languages, undef, 1);
  1866. foreach my $revision (GetKeepRevisions($OpenPageName)) {
  1867. my $keep = GetKeptRevision($revision);
  1868. @languages = split(/,/, $keep->{languages});
  1869. RcTextRevision($id, $keep->{ts}, $keep->{host}, $keep->{username},
  1870. $keep->{summary}, $keep->{minor}, $keep->{revision}, \@languages);
  1871. }
  1872. }
  1873. sub DoHtmlHistory {
  1874. my ($id) = @_;
  1875. print GetHeader('', Ts('History of %s', NormalToFree($id)));
  1876. my $row = 0;
  1877. my $rollback = UserCanEdit($id, 0) && (GetParam('username', '')
  1878. or UserIsEditor());
  1879. my $date = CalcDay($Page{ts});
  1880. my @html = (GetHistoryLine($id, \%Page, $row++, $rollback, $date, 1));
  1881. foreach my $revision (GetKeepRevisions($OpenPageName)) {
  1882. my $keep = GetKeptRevision($revision);
  1883. my $new = CalcDay($keep->{ts});
  1884. push(@html, GetHistoryLine($id, $keep, $row++, $rollback,
  1885. $new, $new ne $date));
  1886. $date = $new;
  1887. }
  1888. @html = (GetFormStart(undef, 'get', 'history'),
  1889. $q->p($q->submit({-name=>T('Compare')}),
  1890. # don't use $q->hidden here!
  1891. $q->input({-type=>'hidden', -name=>'action', -value=>'browse'}),
  1892. $q->input({-type=>'hidden', -name=>'diff', -value=>'1'}),
  1893. $q->input({-type=>'hidden', -name=>'id', -value=>$id})),
  1894. $q->table({-class=>'history'}, @html),
  1895. $q->p($q->submit({-name=>T('Compare')})),
  1896. $q->end_form()) if $UseDiff;
  1897. if ($KeepDays and $rollback and $Page{revision}) {
  1898. push(@html, $q->p(ScriptLink('title=' . UrlEncode($id) . ';text='
  1899. . UrlEncode($DeletedPage) . ';summary='
  1900. . UrlEncode(T('Deleted')),
  1901. T('Mark this page for deletion'))));
  1902. }
  1903. print $q->div({-class=>'content history'}, @html);
  1904. PrintFooter($id, 'history');
  1905. }
  1906. sub GetHistoryLine {
  1907. my ($id, $dataref, $row, $rollback, $date, $newday) = @_;
  1908. my %data = %$dataref;
  1909. my $revision = $data{revision};
  1910. return $q->p(T('No other revisions available')) unless $revision;
  1911. my $html = CalcTime($data{ts});
  1912. if ($row == 0) { # current revision
  1913. $html .= ' (' . T('current') . ')' if $rollback;
  1914. $html .= ' ' . GetPageLink($id, Ts('Revision %s', $revision));
  1915. } else {
  1916. $html .= ' ' . $q->submit("rollback-$data{ts}", T('rollback')) if $rollback;
  1917. $html .= ' ' . GetOldPageLink('browse', $id, $revision,
  1918. Ts('Revision %s', $revision));
  1919. }
  1920. my $host = $data{host} || $data{ip};
  1921. $html .= T(' . . . .') . ' ' . GetAuthorLink($host, $data{username});
  1922. $html .= $q->span({class=>'dash'}, ' &#8211; ')
  1923. . $q->strong(QuoteHtml($data{summary})) if $data{summary};
  1924. $html .= ' ' . $q->em({class=>'type'}, T('(minor)')) . ' ' if $data{minor};
  1925. if ($UseDiff) {
  1926. my %attr1 = (-type=>'radio', -name=>'diffrevision', -value=>$revision);
  1927. $attr1{-checked} = 'checked' if $row == 1;
  1928. my %attr2 = (-type=>'radio', -name=>'revision', -value=> $row ? $revision : '');
  1929. $attr2{-checked} = 'checked' if $row == 0; # first row is special
  1930. $html = $q->Tr($q->td($q->input(\%attr1)), $q->td($q->input(\%attr2)), $q->td($html));
  1931. $html = $q->Tr($q->td({-colspan=>3}, $q->strong($date))) . $html if $newday;
  1932. } else {
  1933. $html .= $q->br();
  1934. $html = $q->strong($date) . $q->br() . $html if $newday;
  1935. }
  1936. return $html;
  1937. }
  1938. sub DoContributors {
  1939. my $id = shift;
  1940. SetParam('rcidonly', $id);
  1941. SetParam('all', 1);
  1942. print GetHeader('', Ts('Contributors to %s', NormalToFree($id || $SiteName)));
  1943. my %contrib = ();
  1944. for my $line (GetRcLines(1)) {
  1945. my ($ts, $pagename, $minor, $summary, $host, $username) = @$line;
  1946. $contrib{$username}++ if $username;
  1947. }
  1948. print $q->div({-class=>'content contrib'},
  1949. $q->p(map { GetPageLink($_) } sort(keys %contrib)));
  1950. PrintFooter();
  1951. }
  1952. sub RollbackPossible {
  1953. my $ts = shift; # there can be no rollback to the most recent change(s) made (1s resolution!)
  1954. return $ts != $LastUpdate && (!$KeepDays || ($Now - $ts) < $KeepDays * 86400); # 24*60*60
  1955. }
  1956. sub DoRollback {
  1957. my $page = shift;
  1958. my $to = GetParam('to', 0);
  1959. ReportError(T('Missing target for rollback.'), '400 BAD REQUEST') unless $to;
  1960. ReportError(T('Target for rollback is too far back.'), '400 BAD REQUEST') unless $page or RollbackPossible($to);
  1961. ReportError(T('A username is required for ordinary users.'), '403 FORBIDDEN') unless GetParam('username', '') or UserIsEditor();
  1962. my @ids = ();
  1963. if (not $page) { # cannot just use list length because of ('')
  1964. return unless UserIsAdminOrError(); # only admins can do mass changes
  1965. SetParam('showedit', 1); # make GetRcLines return minor edits as well
  1966. SetParam('all', 1); # prevent LatestChanges from interfering
  1967. SetParam('rollback', 1); # prevent StripRollbacks from interfering
  1968. my %ids = map { my ($ts, $id) = @$_; $id => 1; } # make unique via hash
  1969. GetRcLines($to); # list all the pages edited since $to
  1970. @ids = keys %ids;
  1971. } else {
  1972. @ids = ($page);
  1973. }
  1974. RequestLockOrError();
  1975. print GetHeader('', T('Rolling back changes')),
  1976. $q->start_div({-class=>'content rollback'}), $q->start_p();
  1977. foreach my $id (@ids) {
  1978. OpenPage($id);
  1979. my ($text, $minor, $ts) = GetTextAtTime($to);
  1980. if ($Page{text} eq $text) {
  1981. print T("The two revisions are the same."), $q->br() if $page; # no message when doing mass revert
  1982. } elsif (not UserCanEdit($id, 1)) {
  1983. print Ts('Editing not allowed: %s is read-only.', $id), $q->br();
  1984. } elsif (not UserIsEditor() and my $rule = BannedContent($text)) {
  1985. print Ts('Rollback of %s would restore banned content.', $id), $rule, $q->br();
  1986. } else {
  1987. Save($id, $text, Ts('Rollback to %s', TimeToText($to)), $minor, ($Page{host} ne $q->remote_addr()));
  1988. print Ts('%s rolled back', GetPageLink($id)), ($ts ? ' ' . Ts('to %s', TimeToText($to)) : ''), $q->br();
  1989. }
  1990. }
  1991. WriteRcLog('[[rollback]]', $page, $to); # leave marker
  1992. print $q->end_p() . $q->end_div();
  1993. ReleaseLock();
  1994. PrintFooter($page, 'edit');
  1995. }
  1996. sub DoAdminPage {
  1997. my ($id, @rest) = @_;
  1998. my @menu = ();
  1999. push(@menu, ScriptLink('action=index', T('Index of all pages'), 'index')) if $Action{index};
  2000. push(@menu, ScriptLink('action=version', T('Wiki Version'), 'version')) if $Action{version};
  2001. push(@menu, ScriptLink('action=password', T('Password'), 'password')) if $Action{password};
  2002. push(@menu, ScriptLink('action=maintain', T('Run maintenance'), 'maintain')) if $Action{maintain};
  2003. my @locks;
  2004. for my $pattern (@KnownLocks) {
  2005. for my $name (bsd_glob $pattern) {
  2006. if (-d $LockDir . $name) {
  2007. push(@locks, $name);
  2008. }
  2009. }
  2010. }
  2011. if (@locks and $Action{unlock}) {
  2012. push(@menu, ScriptLink('action=unlock', T('Unlock Wiki'), 'unlock') . ' (' . join(', ', @locks) . ')');
  2013. };
  2014. if (UserIsAdmin()) {
  2015. if ($Action{editlock}) {
  2016. if (-f "$DataDir/noedit") {
  2017. push(@menu, ScriptLink('action=editlock;set=0', T('Unlock site'), 'editlock 0'));
  2018. } else {
  2019. push(@menu, ScriptLink('action=editlock;set=1', T('Lock site'), 'editlock 1'));
  2020. }
  2021. }
  2022. if ($id and $Action{pagelock}) {
  2023. my $title = NormalToFree($id);
  2024. if (-f GetLockedPageFile($id)) {
  2025. push(@menu, ScriptLink('action=pagelock;set=0;id=' . UrlEncode($id),
  2026. Ts('Unlock %s', $title), 'pagelock 0'));
  2027. } else {
  2028. push(@menu, ScriptLink('action=pagelock;set=1;id=' . UrlEncode($id),
  2029. Ts('Lock %s', $title), 'pagelock 1'));
  2030. }
  2031. }
  2032. push(@menu, ScriptLink('action=clear', T('Clear Cache'), 'clear')) if $Action{clear};
  2033. }
  2034. foreach my $sub (@MyAdminCode) {
  2035. $sub->($id, \@menu, \@rest);
  2036. $Message .= $q->p($@) if $@; # since this happens before GetHeader is called, the message will be shown
  2037. }
  2038. print GetHeader('', T('Administration')),
  2039. $q->div({-class=>'content admin'}, $q->p(T('Actions:')), $q->ul($q->li(\@menu)),
  2040. $q->p(T('Important pages:')) . $q->ul(map { $q->li(GetPageOrEditLink($_, NormalToFree($_))) if $_;
  2041. } sort keys %AdminPages),
  2042. $q->p(Ts('To mark a page for deletion, put <strong>%s</strong> on the first line.',
  2043. $DeletedPage)), @rest);
  2044. PrintFooter();
  2045. }
  2046. sub GetPageParameters {
  2047. my ($action, $id, $revision, $cluster, $last) = @_;
  2048. $id = FreeToNormal($id);
  2049. my $link = "action=$action;id=" . UrlEncode($id);
  2050. $link .= ";revision=$revision" if $revision and not $last;
  2051. $link .= ';rcclusteronly=' . UrlEncode($cluster) if $cluster;
  2052. return $link;
  2053. }
  2054. sub GetOldPageLink {
  2055. my ($action, $id, $revision, $name, $cluster, $last) = @_;
  2056. return ScriptLink(GetPageParameters($action, $id, $revision, $cluster, $last),
  2057. NormalToFree($name), 'revision');
  2058. }
  2059. sub GetSearchLink {
  2060. my ($text, $class, $name, $title) = @_;
  2061. my $id = UrlEncode(QuoteRegexp('"' . $text . '"'));
  2062. $name = UrlEncode($name);
  2063. $text = NormalToFree($text);
  2064. $id =~ s/_/+/g; # Search for url-escaped spaces
  2065. return ScriptLink('search=' . $id, $text, $class, $name, $title);
  2066. }
  2067. sub ScriptLinkDiff {
  2068. my ($diff, $id, $text, $new, $old) = @_;
  2069. my $action = 'action=browse;diff=' . $diff . ';id=' . UrlEncode($id);
  2070. $action .= ";diffrevision=$old" if $old;
  2071. $action .= ";revision=$new" if $new;
  2072. return ScriptLink($action, $text, 'diff');
  2073. }
  2074. sub GetAuthor {
  2075. my ($host, $username) = @_;
  2076. return $username . ' ' . Ts('from %s', $host) if $username and $host;
  2077. return $username if $username;
  2078. return T($host); # could be 'Anonymous'
  2079. }
  2080. sub GetAuthorLink {
  2081. my ($host, $username) = @_;
  2082. $username = FreeToNormal($username);
  2083. my $name = NormalToFree($username);
  2084. if (ValidId($username) ne '') { # ValidId() returns error string
  2085. $username = ''; # Just pretend it isn't there.
  2086. }
  2087. if ($username and $RecentLink) {
  2088. return ScriptLink(UrlEncode($username), $name, 'author', undef, $host);
  2089. } elsif ($username) {
  2090. return $q->span({-class=>'author'}, $name);
  2091. }
  2092. return T($host); # could be 'Anonymous'
  2093. }
  2094. sub GetHistoryLink {
  2095. my ($id, $text) = @_;
  2096. my $action = 'action=history;id=' . UrlEncode(FreeToNormal($id));
  2097. return ScriptLink($action, $text, 'history');
  2098. }
  2099. sub GetRCLink {
  2100. my ($id, $text) = @_;
  2101. return ScriptLink('action=rc;all=1;from=1;showedit=1;rcidonly='
  2102. . UrlEncode(FreeToNormal($id)), $text, 'rc');
  2103. }
  2104. sub GetHeader {
  2105. my ($id, $title, $oldId, $nocache, $status) = @_;
  2106. my $embed = GetParam('embed', $EmbedWiki);
  2107. my $result = GetHttpHeader('text/html', $nocache, $status);
  2108. if ($oldId) {
  2109. $Message .= $q->p('(' . Ts('redirected from %s', GetEditLink($oldId, $oldId)) . ')');
  2110. }
  2111. $result .= GetHtmlHeader(Ts('%s:', $SiteName) . ' ' . UnWiki($title), $id);
  2112. if ($embed) {
  2113. $result .= $q->div({-class=>'header'}, $q->div({-class=>'message'}, $Message)) if $Message;
  2114. return $result;
  2115. }
  2116. $result .= GetHeaderDiv($id, $title, $oldId, $embed);
  2117. return $result . $q->start_div({-class=>'wrapper'});
  2118. }
  2119. sub GetHeaderDiv {
  2120. my ($id, $title, $oldId, $embed) = @_;
  2121. my $result .= $q->start_div({-class=>'header'});
  2122. if (not $embed and $LogoUrl) {
  2123. my $url = $IndexHash{$LogoUrl} ? GetDownloadLink($LogoUrl, 2) : $LogoUrl;
  2124. $result .= ScriptLink(UrlEncode($HomePage), $q->img({-src=>$url, -alt=>T('[Home]'), -class=>'logo'}), 'logo');
  2125. }
  2126. $result .= $q->start_div({-class=>'menu'});
  2127. if (GetParam('toplinkbar', $TopLinkBar) != 2) {
  2128. $result .= GetGotoBar($id);
  2129. if (%SpecialDays) {
  2130. my ($sec, $min, $hour, $mday, $mon, $year) = gmtime($Now);
  2131. if ($SpecialDays{($mon + 1) . '-' . $mday}) {
  2132. $result .= $q->br() . $q->span({-class=>'specialdays'},
  2133. $SpecialDays{($mon + 1) . '-' . $mday});
  2134. }
  2135. }
  2136. }
  2137. $result .= GetSearchForm() if GetParam('topsearchform', $TopSearchForm) != 2;
  2138. $result .= $q->end_div();
  2139. $result .= $q->div({-class=>'message'}, $Message) if $Message;
  2140. $result .= GetHeaderTitle($id, $title, $oldId);
  2141. $result .= $q->end_div();
  2142. return $result;
  2143. }
  2144. sub GetHeaderTitle {
  2145. my ($id, $title, $oldId) = @_;
  2146. return $q->h1($title) if $id eq '';
  2147. return $q->h1(GetSearchLink($id, '', '', T('Click to search for references to this page')));
  2148. }
  2149. sub GetHttpHeader {
  2150. return if $HeaderIsPrinted; # When calling ReportError, we don't know whether HTTP headers have
  2151. $HeaderIsPrinted = 1; # already been printed. We want them printed just once.
  2152. my ($type, $ts, $status, $encoding) = @_;
  2153. $q->charset($type =~ m!^(text/|application/xml)! ? 'utf-8' : ''); # text/plain, text/html, application/xml: UTF-8
  2154. my %headers = (-cache_control=>($UseCache < 0 ? 'no-cache' : 'max-age=10'));
  2155. # Set $ts when serving raw content that cannot be modified by cookie
  2156. # parameters; or 'nocache'; or undef. If you provide a $ts, the last-modified
  2157. # header generated will by used by HTTP/1.0 clients. If you provide no $ts,
  2158. # the etag header generated will be used by HTTP/1.1 clients. In this
  2159. # situation, cookie parameters can influence the look of the page and we
  2160. # cannot rely on $LastUpdate. HTTP/1.0 clients will ignore etags. See RFC 2616
  2161. # section 13.3.4.
  2162. if (GetParam('cache', $UseCache) >= 2 and $ts ne 'nocache') {
  2163. $headers{'-last-modified'} = TimeToRFC822($ts) if $ts;
  2164. $headers{-etag} = PageEtag();
  2165. }
  2166. $headers{-type} = GetParam('mime-type', $type);
  2167. $headers{-status} = $status if $status;
  2168. $headers{-Content_Encoding} = $encoding if $encoding;
  2169. my $cookie = Cookie();
  2170. $headers{-cookie} = $cookie if $cookie;
  2171. if ($q->request_method() eq 'HEAD') {
  2172. print $q->header(%headers), "\n\n"; # add newlines for FCGI because of exit()
  2173. exit; # total shortcut -- HEAD never expects anything other than the header!
  2174. }
  2175. return $q->header(%headers);
  2176. }
  2177. sub CookieData {
  2178. my ($changed, %params);
  2179. foreach my $key (keys %CookieParameters) {
  2180. my $default = $CookieParameters{$key};
  2181. my $value = GetParam($key, $default);
  2182. $params{$key} = $value if $value ne $default;
  2183. # The cookie is considered to have changed under the following
  2184. # condition: If the value was already set, and the new value is
  2185. # not the same as the old value, or if there was no old value, and
  2186. # the new value is not the default.
  2187. my $change = (defined $OldCookie{$key} ? ($value ne $OldCookie{$key}) : ($value ne $default));
  2188. $changed = 1 if $change; # note if any parameter changed and needs storing
  2189. }
  2190. return $changed, %params;
  2191. }
  2192. sub Cookie {
  2193. my ($changed, %params) = CookieData(); # params are URL encoded
  2194. if ($changed) {
  2195. my $cookie = join(UrlEncode($FS), %params); # no CTL in field values
  2196. return $q->cookie(-name=>$CookieName, -value=>$cookie, -expires=>'+2y', secure=>$ENV{'HTTPS'}, httponly=>1);
  2197. }
  2198. return '';
  2199. }
  2200. sub GetHtmlHeader { # always HTML!
  2201. my ($title, $id) = @_;
  2202. my $edit_link = '';
  2203. $edit_link = '<link rel="alternate" type="application/wiki" title="'
  2204. . T('Edit this page') . '" href="'
  2205. . ScriptUrl('action=edit;id=' . UrlEncode($id)) . '" />' if $id;
  2206. return $DocumentHeader
  2207. . $q->head($q->title($title) . $edit_link
  2208. . GetCss() . GetRobots() . GetFeeds() . $HtmlHeaders
  2209. . '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />')
  2210. . '<body class="' . GetParam('theme', 'default') . '">';
  2211. }
  2212. sub GetRobots { # NOINDEX for non-browse pages.
  2213. if (GetParam('action', 'browse') eq 'browse' and not GetParam('revision', '')) {
  2214. return '<meta name="robots" content="INDEX,FOLLOW" />';
  2215. } else {
  2216. return '<meta name="robots" content="NOINDEX,FOLLOW" />';
  2217. }
  2218. }
  2219. sub GetFeeds { # default for $HtmlHeaders
  2220. my $html = '<link rel="alternate" type="application/rss+xml" title="'
  2221. . QuoteHtml($SiteName) . '" href="' . $ScriptName . '?action=rss" />';
  2222. my $id = GetId(); # runs during Init, not during DoBrowseRequest
  2223. $html .= '<link rel="alternate" type="application/rss+xml" title="'
  2224. . QuoteHtml("$SiteName: $id") . '" href="' . $ScriptName
  2225. . '?action=rss;rcidonly=' . UrlEncode(FreeToNormal($id)) . '" />' if $id;
  2226. my $username = GetParam('username', '');
  2227. $html .= '<link rel="alternate" type="application/rss+xml" '
  2228. . 'title="Follow-ups for ' . NormalToFree($username) . '" '
  2229. . 'href="' . ScriptUrl('action=rss;followup=' . UrlEncode($username))
  2230. . '" />' if $username;
  2231. return $html;
  2232. }
  2233. sub GetCss { # prevent javascript injection
  2234. my @css = map { my $x = $_; $x =~ s/\".*//; $x; } split(/\s+/, GetParam('css', ''));
  2235. push (@css, ref $StyleSheet ? @$StyleSheet : $StyleSheet) if $StyleSheet and not @css;
  2236. if ($IndexHash{$StyleSheetPage} and not @css) {
  2237. push (@css, "$ScriptName?action=browse;id=" . UrlEncode($StyleSheetPage) . ";raw=1;mime-type=text/css")
  2238. }
  2239. push (@css, 'https://oddmuse.org/default.css') unless @css;
  2240. return join('', map { qq(<link type="text/css" rel="stylesheet" href="$_" />) } @css);
  2241. }
  2242. sub PrintPageContent {
  2243. my ($text, $revision, $comment) = @_;
  2244. print $q->start_div({-class=>'content browse'});
  2245. if ($revision eq '' and $Page{blocks} and GetParam('cache', $UseCache) > 0) {
  2246. PrintCache();
  2247. } else {
  2248. my $savecache = ($Page{revision} > 0 and $revision eq ''); # new page not cached
  2249. PrintWikiToHTML($text, $savecache, $revision); # unlocked, with anchors, unlocked
  2250. }
  2251. if ($comment) {
  2252. print $q->start_div({-class=>'preview'}), $q->hr();
  2253. print $q->h2(T('Preview:'));
  2254. # no caching, current revision, unlocked
  2255. PrintWikiToHTML(AddComment('', $comment));
  2256. print $q->hr(), $q->h2(T('Preview only, not yet saved')), $q->end_div();
  2257. }
  2258. print $q->end_div();
  2259. }
  2260. sub PrintFooter {
  2261. my ($id, $rev, $comment, $page) = @_;
  2262. if (GetParam('embed', $EmbedWiki)) {
  2263. print $q->end_html, "\n";
  2264. return;
  2265. }
  2266. PrintMyContent($id) if defined(&PrintMyContent);
  2267. foreach my $sub (@MyFooters) {
  2268. print $sub->(@_);
  2269. }
  2270. print $q->end_html, "\n";
  2271. }
  2272. sub WrapperEnd { # called via @MyFooters
  2273. return $q->start_div({-class=>'wrapper close'}) . $q->end_div() . $q->end_div(); # closes content
  2274. }
  2275. sub DefaultFooter { # called via @MyFooters
  2276. my ($id, $rev, $comment, $page) = @_;
  2277. my $html = $q->start_div({-class=>'footer'}) . $q->hr();
  2278. $html .= GetGotoBar($id) if GetParam('toplinkbar', $TopLinkBar) != 1;
  2279. $html .= GetFooterLinks($id, $rev);
  2280. $html .= GetFooterTimestamp($id, $rev, $page);
  2281. $html .= GetSearchForm() if GetParam('topsearchform', $TopSearchForm) != 1;
  2282. if ($DataDir =~ m|/tmp/|) {
  2283. $html .= $q->p($q->strong(T('Warning') . ': ')
  2284. . Ts('Database is stored in temporary directory %s', $DataDir));
  2285. }
  2286. $html .= T($FooterNote) if $FooterNote;
  2287. $html .= $q->p(Ts('%s seconds', (time - $Now))) if GetParam('timing', 0);
  2288. $html .= $q->end_div();
  2289. return $html;
  2290. }
  2291. sub GetFooterTimestamp {
  2292. my ($id, $rev, $page) = @_;
  2293. $page //= \%Page;
  2294. if ($id and $rev ne 'history' and $rev ne 'edit' and $page->{revision}) {
  2295. my @elements = (($rev eq '' ? T('Last edited') : T('Edited')), TimeToText($page->{ts}),
  2296. Ts('by %s', GetAuthorLink($page->{host}, $page->{username})));
  2297. push(@elements, ScriptLinkDiff(2, $id, T('(diff)'), $rev)) if $UseDiff and $page->{revision} > 1;
  2298. return $q->div({-class=>'time'}, @elements);
  2299. }
  2300. return '';
  2301. }
  2302. sub GetFooterLinks {
  2303. my ($id, $rev) = @_;
  2304. my @elements;
  2305. if ($id and $rev ne 'history' and $rev ne 'edit') {
  2306. if ($CommentsPattern) {
  2307. if ($id =~ /$CommentsPattern/) {
  2308. push(@elements, GetPageLink($1, undef, 'original', T('a'))) if $1;
  2309. } else {
  2310. push(@elements, GetPageLink($CommentsPrefix . $id, undef, 'comment', T('c')));
  2311. }
  2312. }
  2313. if (UserCanEdit($id, 0)) {
  2314. if ($rev) { # showing old revision
  2315. push(@elements, GetOldPageLink('edit', $id, $rev, Ts('Edit revision %s of this page', $rev)));
  2316. } else { # showing current revision
  2317. push(@elements, GetEditLink($id, T('Edit this page'), undef, T('e')));
  2318. }
  2319. } else { # no permission or generated page
  2320. push(@elements, ScriptLink('action=password', T('This page is read-only'), 'password'));
  2321. }
  2322. }
  2323. push(@elements, GetHistoryLink($id, T('View other revisions'))) if $Action{history} and $id and $rev ne 'history';
  2324. push(@elements, GetPageLink($id, T('View current revision')),
  2325. GetRCLink($id, T('View all changes'))) if $Action{history} and $rev ne '';
  2326. if ($Action{contrib} and $id and $rev eq 'history') {
  2327. push(@elements, ScriptLink("action=contrib;id=" . UrlEncode($id), T('View contributors'), 'contrib'));
  2328. }
  2329. if ($Action{admin} and GetParam('action', '') ne 'admin') {
  2330. my $action = 'action=admin';
  2331. $action .= ';id=' . UrlEncode($id) if $id;
  2332. push(@elements, ScriptLink($action, T('Administration'), 'admin'));
  2333. }
  2334. return @elements ? $q->div({-class=>'edit bar'}, @elements) : '';
  2335. }
  2336. sub GetCommentForm {
  2337. my ($id, $rev, $comment) = @_;
  2338. if ($CommentsPattern ne '' and $id and $rev ne 'history' and $rev ne 'edit'
  2339. and $id =~ /$CommentsPattern/ and UserCanEdit($id, 0, 1)) {
  2340. my $html = $q->div({-class=>'comment'},
  2341. GetFormStart(undef, undef, 'comment'),
  2342. $q->p(GetHiddenValue('title', $id),
  2343. $q->label({-for=>'aftertext', -accesskey=>T('c')},
  2344. T('Add your comment here:')), $q->br(),
  2345. GetTextArea('aftertext', $comment, 10)),
  2346. $EditNote,
  2347. $q->p($q->span({-class=>'username'},
  2348. $q->label({-for=>'username'}, T('Username:')), ' ',
  2349. $q->textfield(-name=>'username', -id=>'username',
  2350. -default=>GetParam('username', ''),
  2351. -override=>1, -size=>20, -maxlength=>50)),
  2352. $q->span({-class=>'homepage'},
  2353. $q->label({-for=>'homepage'}, T('Homepage URL:')), ' ',
  2354. $q->textfield(-name=>'homepage', -id=>'homepage',
  2355. -default=>GetParam('homepage', ''),
  2356. -override=>1, -size=>40, -maxlength=>100))),
  2357. $q->p($q->submit(-name=>'Save', -accesskey=>T('s'), -value=>T('Save')), ' ',
  2358. $q->submit(-name=>'Preview', -accesskey=>T('p'), -value=>T('Preview'))),
  2359. $q->end_form());
  2360. foreach my $sub (@MyFormChanges) {
  2361. $html = $sub->($html, 'comment');
  2362. }
  2363. return $html;
  2364. }
  2365. return '';
  2366. }
  2367. sub GetFormStart {
  2368. my ($ignore, $method, $class) = @_;
  2369. $method ||= 'post';
  2370. $class ||= 'form';
  2371. return $q->start_multipart_form(-method=>$method, -action=>$FullUrl,
  2372. -accept_charset=>'utf-8', -class=>$class);
  2373. }
  2374. sub GetSearchForm {
  2375. my $html = GetFormStart(undef, 'get', 'search') . $q->start_p;
  2376. $html .= $q->label({-for=>'search'}, T('Search:')) . ' '
  2377. . $q->textfield(-name=>'search', -id=>'search', -size=>20, -accesskey=>T('f')) . ' ';
  2378. if (GetParam('search') ne '' and UserIsAdmin()) { # see DoBrowseRequest
  2379. $html .= $q->label({-for=>'replace'}, T('Replace:')) . ' '
  2380. . $q->textfield(-name=>'replace', -id=>'replace', -size=>20) . ' '
  2381. . $q->label({-for=>'delete', -title=>'If you want to replace matches with the empty string'}, T('Delete')) . ' '
  2382. . $q->input({-type=>'checkbox', -name=>'delete'})
  2383. . $q->submit('preview', T('Preview'));
  2384. }
  2385. if (GetParam('matchingpages', $MatchingPages)) {
  2386. $html .= $q->label({-for=>'matchingpage'}, T('Filter:')) . ' '
  2387. . $q->textfield(-name=>'match', -id=>'matchingpage', -size=>20) . ' ';
  2388. }
  2389. if (%Languages) {
  2390. $html .= $q->label({-for=>'searchlang'}, T('Language:')) . ' '
  2391. . $q->textfield(-name=>'lang', -id=>'searchlang', -size=>10, -default=>GetParam('lang', '')) . ' ';
  2392. }
  2393. $html .= $q->submit('dosearch', T('Go!')) . $q->end_p . $q->end_form;
  2394. return $html;
  2395. }
  2396. sub GetGotoBar { # ignore $id parameter
  2397. return $q->span({-class=>'gotobar bar'}, (map { GetPageLink($_) }
  2398. @UserGotoBarPages), $UserGotoBar);
  2399. }
  2400. sub PrintHtmlDiff {
  2401. my ($type, $old, $page, $current) = @_;
  2402. $page //= \%Page;
  2403. $current //= $page->{revision};
  2404. $type = 2 if $old or $page->{revision} != $current; # explicit revisions means minor diffs!
  2405. my $summary = $page->{$type == 1 ? 'lastmajorsummary' : 'summary'};
  2406. my $intro = T('Last edit');
  2407. my $diff;
  2408. # use the cached diff if possible
  2409. if (not $old or $old == $page->{$type == 1 ? 'lastmajor' : 'revision'} - 1) {
  2410. $diff = GetCacheDiff($type == 1 ? 'major' : 'minor', $page);
  2411. $old = $page->{$type == 1 ? 'lastmajor' : 'revision'} - 1 if not $old;
  2412. }
  2413. # if there was no cached diff: compute it, and new intro
  2414. if (not $diff and $old > 0) {
  2415. ($diff, my $keptPage) = GetKeptDiff($page->{text}, $old);
  2416. my $to = $page->{revision} != $current ? Ts('revision %s', $page->{revision}) : T('current revision');
  2417. $intro = Tss('Difference between revision %1 and %2', $old, $to);
  2418. }
  2419. # if this is the last major diff and there are minor diffs to look at, and we
  2420. # didn't request a particular old revision
  2421. if ($type == 1 and $page->{lastmajor} and $page->{lastmajor} != $current) {
  2422. $intro = Ts('Last major edit (%s)', ScriptLinkDiff(2, $OpenPageName, T('later minor edits'),
  2423. undef, $page->{lastmajor} || 1));
  2424. }
  2425. $diff =~ s!<p><strong>(.*?)</strong></p>!'<p><strong>' . T($1) . '</strong></p>'!eg;
  2426. $diff ||= T('No diff available.');
  2427. print $q->div({-class=>'diff'}, $q->p($q->b($intro)),
  2428. $summary ? $q->p({-class=>'summary'}, T('Summary:') . ' ' . QuoteHtml($summary)) : '',
  2429. $diff);
  2430. }
  2431. sub GetCacheDiff {
  2432. my ($type, $page) = @_;
  2433. my $diff = $page->{"diff-$type"};
  2434. $diff = $page->{"diff-minor"} if $diff eq '1'; # if major eq minor diff
  2435. return $diff;
  2436. }
  2437. sub GetKeptDiff {
  2438. my ($new, $revision) = @_;
  2439. $revision ||= 1;
  2440. my ($revisionPage, $rev) = GetTextRevision($revision, 1);
  2441. return '', $revisionPage unless $rev;
  2442. return T("The two revisions are the same."), $revisionPage if $revisionPage->{text} eq $new;
  2443. return GetDiff($revisionPage->{text}, $new, $rev), $revisionPage;
  2444. }
  2445. sub DoDiff { # Actualy call the diff program
  2446. CreateDir($TempDir);
  2447. my $oldName = "$TempDir/old";
  2448. my $newName = "$TempDir/new";
  2449. RequestLockDir('diff') or return '';
  2450. WriteStringToFile($oldName, $_[0]);
  2451. WriteStringToFile($newName, $_[1]);
  2452. my $diff_out = `diff -- \Q$oldName\E \Q$newName\E`;
  2453. utf8::decode($diff_out); # needs decoding
  2454. $diff_out =~ s/\n\K\\ No newline.*\n//g; # Get rid of common complaint.
  2455. ReleaseLockDir('diff');
  2456. # No need to unlink temp files--next diff will just overwrite.
  2457. return $diff_out;
  2458. }
  2459. sub GetDiff {
  2460. my ($old, $new, $revision) = @_;
  2461. my $old_is_file = (TextIsFile($old))[0] || '';
  2462. my $old_is_image = ($old_is_file =~ /^image\//);
  2463. my $new_is_file = TextIsFile($new);
  2464. if ($old_is_file or $new_is_file) {
  2465. return $q->p($q->strong(T('Old revision:')))
  2466. . $q->div({-class=>'old'}, # don't pring new revision, because that's the one that gets shown!
  2467. $q->p($old_is_file ? GetDownloadLink($OpenPageName, $old_is_image, $revision) : $old))
  2468. }
  2469. $old =~ s/[\r\n]+/\n/g;
  2470. $new =~ s/[\r\n]+/\n/g;
  2471. return ImproveDiff(DoDiff($old, $new));
  2472. }
  2473. sub ImproveDiff { # NO NEED TO BE called within a diff lock
  2474. my $diff = QuoteHtml(shift);
  2475. $diff =~ tr/\r//d;
  2476. my @hunks = split (/^(\d+,?\d*[adc]\d+,?\d*\n)/m, $diff);
  2477. my $result = shift (@hunks); # intro
  2478. while ($#hunks > 0) { # at least one header and a real hunk
  2479. my $header = shift (@hunks);
  2480. $header =~ s|^(\d+.*c.*)|<p><strong>Changed:</strong></p>| # T('Changed:')
  2481. or $header =~ s|^(\d+.*d.*)|<p><strong>Deleted:</strong></p>| # T('Deleted:')
  2482. or $header =~ s|^(\d+.*a.*)|<p><strong>Added:</strong></p>|; # T('Added:')
  2483. $result .= $header;
  2484. my $chunk = shift (@hunks);
  2485. my ($old, $new) = split (/\n---\n/, $chunk, 2);
  2486. if ($old and $new) {
  2487. ($old, $new) = DiffMarkWords($old, $new);
  2488. $result .= "$old<p><strong>to</strong></p>\n$new"; # T('to')
  2489. } else {
  2490. if (substr($chunk, 0, 2) eq '&g') {
  2491. $result .= DiffAddPrefix(DiffStripPrefix($chunk), '&gt; ', 'new');
  2492. } else {
  2493. $result .= DiffAddPrefix(DiffStripPrefix($chunk), '&lt; ', 'old');
  2494. }
  2495. }
  2496. }
  2497. return $result;
  2498. }
  2499. sub DiffMarkWords {
  2500. my ($old, $new) = map { DiffStripPrefix($_) } @_;
  2501. my @diffs = grep(/^\d/, split(/\n/, DoDiff(join("\n", split(/\s+|\b/, $old)) . "\n",
  2502. join("\n", split(/\s+|\b/, $new)) . "\n")));
  2503. foreach my $diff (reverse @diffs) { # so that new html tags don't confuse word counts
  2504. my ($start1, $end1, $type, $start2, $end2) = $diff =~ /^(\d+),?(\d*)([adc])(\d+),?(\d*)$/gm;
  2505. if ($type eq 'd' or $type eq 'c') {
  2506. $end1 ||= $start1;
  2507. $old = DiffHtmlMarkWords($old, $start1, $end1);
  2508. }
  2509. if ($type eq 'a' or $type eq 'c') {
  2510. $end2 ||= $start2;
  2511. $new = DiffHtmlMarkWords($new, $start2, $end2);
  2512. }
  2513. }
  2514. return (DiffAddPrefix($old, '&lt; ', 'old'),
  2515. DiffAddPrefix($new, '&gt; ', 'new'));
  2516. }
  2517. sub DiffHtmlMarkWords {
  2518. my ($text, $start, $end) = @_;
  2519. my @fragments = split(/(\s+|\b)/, $text);
  2520. splice(@fragments, 2 * ($start - 1), 0, '<strong class="changes">');
  2521. splice(@fragments, 2 * $end, 0, '</strong>');
  2522. my $result = join('', @fragments);
  2523. $result =~ s!&<(/?)strong([^>]*)>(amp|[gl]t);!<$1strong$2>&$3;!g;
  2524. $result =~ s!&(amp|[gl]t)<(/?)strong([^>]*)>;!&$1;<$2strong$3>!g;
  2525. return $result;
  2526. }
  2527. sub DiffStripPrefix {
  2528. my $str = shift;
  2529. $str =~ s/^&[lg]t; //gm;
  2530. return $str;
  2531. }
  2532. sub DiffAddPrefix {
  2533. my ($str, $prefix, $class) = @_;
  2534. my @lines = split(/\n/, $str);
  2535. for my $line (@lines) {
  2536. $line = $prefix . $line;
  2537. }
  2538. return $q->div({-class=>$class}, $q->p(join($q->br(), @lines)));
  2539. }
  2540. sub ParseData {
  2541. my $data = shift;
  2542. my %result;
  2543. while ($data =~ /(\S+?): (.*?)(?=\n[^ \t]|\Z)/gs) {
  2544. my ($key, $value) = ($1, $2);
  2545. $value =~ s/\n\t/\n/g;
  2546. $result{$key} = $value;
  2547. }
  2548. # return unless %result; # undef instead of empty hash # TODO should we do that?
  2549. return wantarray ? %result : \%result; # return list sometimes for compatibility
  2550. }
  2551. sub OpenPage { # Sets global variables
  2552. my $id = shift;
  2553. return if $OpenPageName eq $id;
  2554. if ($IndexHash{$id}) {
  2555. %Page = %{ParseData(ReadFileOrDie(GetPageFile($id)))};
  2556. } else {
  2557. %Page = ();
  2558. $Page{ts} = $Now;
  2559. $Page{revision} = 0;
  2560. }
  2561. $OpenPageName = $id;
  2562. }
  2563. sub GetTextAtTime { # call with opened page, return $minor if all pages between now and $ts are minor!
  2564. my $ts = shift;
  2565. my $minor = $Page{minor};
  2566. return ($Page{text}, $minor, 0) if $Page{ts} <= $ts; # current page is old enough
  2567. return ($DeletedPage, $minor, 0) if $Page{revision} == 1 and $Page{ts} > $ts; # created after $ts
  2568. my $keep = {}; # info may be needed after the loop
  2569. foreach my $revision (GetKeepRevisions($OpenPageName)) {
  2570. $keep = GetKeptRevision($revision);
  2571. # $minor = 0 unless defined $keep; # TODO?
  2572. $minor = 0 if not $keep->{minor} and $keep->{ts} >= $ts; # ignore keep{minor} if keep{ts} is too old
  2573. return ($keep->{text}, $minor, 0) if $keep->{ts} <= $ts;
  2574. }
  2575. return ($DeletedPage, $minor, 0) if $keep->{revision} == 1; # then the page was created after $ts!
  2576. return ($keep->{text}, $minor, $keep->{ts}); # the oldest revision available is not old enough
  2577. }
  2578. sub GetTextRevision {
  2579. my ($revision, $quiet) = @_;
  2580. $revision =~ s/\D//g; # Remove non-numeric chars
  2581. return wantarray ? (\%Page, $revision) : \%Page unless $revision and $revision ne $Page{revision};
  2582. my $keep = GetKeptRevision($revision);
  2583. if (not defined $keep) {
  2584. $Message .= $q->p(Ts('Revision %s not available', $revision)
  2585. . ' (' . T('showing current revision instead') . ')') unless $quiet;
  2586. return wantarray ? (\%Page, '') : \%Page;
  2587. }
  2588. $Message .= $q->p(Ts('Showing revision %s', $revision)) unless $quiet;
  2589. return wantarray ? ($keep, $revision) : $keep;
  2590. }
  2591. sub GetPageContent {
  2592. my $id = shift;
  2593. return ParseData(ReadFileOrDie(GetPageFile($id)))->{text} if $IndexHash{$id};
  2594. return '';
  2595. }
  2596. sub GetKeptRevision { # Call after OpenPage
  2597. my ($status, $data) = ReadFile(GetKeepFile($OpenPageName, (shift)));
  2598. return unless $status;
  2599. return ParseData($data);
  2600. }
  2601. sub GetPageFile {
  2602. my ($id) = @_;
  2603. return "$PageDir/$id.pg";
  2604. }
  2605. sub GetKeepFile {
  2606. my ($id, $revision) = @_; die "No revision for $id" unless $revision; #FIXME
  2607. return GetKeepDir($id) . "/$revision.kp";
  2608. }
  2609. sub GetKeepDir {
  2610. my $id = shift; die 'No id' unless $id; #FIXME
  2611. return "$KeepDir/$id";
  2612. }
  2613. sub GetKeepFiles {
  2614. return bsd_glob(GetKeepDir(shift) . '/*.kp'); # files such as 1.kp, 2.kp, etc.
  2615. }
  2616. sub GetKeepRevisions {
  2617. my @result = sort {$b <=> $a} map { m/([0-9]+)\.kp$/; $1; } GetKeepFiles(shift);
  2618. return @result;
  2619. }
  2620. # Always call SavePage within a lock.
  2621. sub SavePage { # updating the cache will not change timestamp and revision!
  2622. ReportError(T('Cannot save a nameless page.'), '400 BAD REQUEST', 1) unless $OpenPageName;
  2623. ReportError(T('Cannot save a page without revision.'), '400 BAD REQUEST', 1) unless $Page{revision};
  2624. CreateDir($PageDir);
  2625. WriteStringToFile(GetPageFile($OpenPageName), EncodePage(%Page));
  2626. }
  2627. sub SaveKeepFile {
  2628. return if ($Page{revision} < 1); # Don't keep 'empty' revision
  2629. delete $Page{blocks}; # delete some info from the page
  2630. delete $Page{flags};
  2631. delete $Page{'diff-major'};
  2632. delete $Page{'diff-minor'};
  2633. $Page{'keep-ts'} = $Now; # expire only $KeepDays from $Now!
  2634. CreateDir($KeepDir);
  2635. CreateDir(GetKeepDir($OpenPageName));
  2636. WriteStringToFile(GetKeepFile($OpenPageName, $Page{revision}), EncodePage(%Page));
  2637. }
  2638. sub EncodePage {
  2639. my @data = @_;
  2640. my $result = '';
  2641. $result .= (shift @data) . ': ' . EscapeNewlines(shift @data) . "\n" while (@data);
  2642. return $result;
  2643. }
  2644. sub EscapeNewlines {
  2645. $_[0] =~ s/\n/\n\t/g; # modify original instead of copying
  2646. return $_[0];
  2647. }
  2648. sub ExpireAllKeepFiles {
  2649. foreach my $name (AllPagesList()) {
  2650. print $q->br(), GetPageLink($name);
  2651. OpenPage($name);
  2652. my $delete = PageDeletable();
  2653. if ($delete) {
  2654. my $status = DeletePage($OpenPageName);
  2655. print ' ', ($status ? T('not deleted:') . ' ' . $status : T('deleted'));
  2656. } else {
  2657. ExpireKeepFiles();
  2658. }
  2659. }
  2660. }
  2661. sub ExpireKeepFiles { # call with opened page
  2662. return unless $KeepDays;
  2663. my $expirets = $Now - ($KeepDays * 86400); # 24*60*60
  2664. foreach my $revision (GetKeepRevisions($OpenPageName)) {
  2665. my $keep = GetKeptRevision($revision);
  2666. next if $keep->{'keep-ts'} >= $expirets;
  2667. next if $KeepMajor and $keep->{revision} == $Page{lastmajor};
  2668. unlink GetKeepFile($OpenPageName, $revision);
  2669. }
  2670. }
  2671. sub ReadFile {
  2672. my $file = shift;
  2673. utf8::encode($file); # filenames are bytes!
  2674. if (open(my $IN, '<:encoding(UTF-8)', $file)) {
  2675. local $/ = undef; # Read complete files
  2676. my $data=<$IN>;
  2677. close $IN;
  2678. return (1, $data);
  2679. }
  2680. return (0, '');
  2681. }
  2682. sub ReadFileOrDie {
  2683. my ($file) = @_;
  2684. my ($status, $data);
  2685. ($status, $data) = ReadFile($file);
  2686. if (not $status) {
  2687. ReportError(Ts('Cannot open %s', $file) . ": $!", '500 INTERNAL SERVER ERROR');
  2688. }
  2689. return $data;
  2690. }
  2691. sub WriteStringToFile {
  2692. my ($file, $string) = @_;
  2693. utf8::encode($file);
  2694. open(my $OUT, '>:encoding(UTF-8)', $file)
  2695. or ReportError(Ts('Cannot write %s', $file) . ": $!", '500 INTERNAL SERVER ERROR');
  2696. print $OUT $string;
  2697. close($OUT);
  2698. }
  2699. sub AppendStringToFile {
  2700. my ($file, $string) = @_;
  2701. utf8::encode($file);
  2702. open(my $OUT, '>>:encoding(UTF-8)', $file)
  2703. or ReportError(Ts('Cannot write %s', $file) . ": $!", '500 INTERNAL SERVER ERROR');
  2704. print $OUT $string;
  2705. close($OUT);
  2706. }
  2707. sub CreateDir {
  2708. my ($newdir) = @_;
  2709. utf8::encode($newdir);
  2710. return if -d $newdir;
  2711. mkdir($newdir, 0775)
  2712. or ReportError(Ts('Cannot create %s', $newdir) . ": $!", '500 INTERNAL SERVER ERROR');
  2713. }
  2714. sub GetLockedPageFile {
  2715. my $id = shift;
  2716. return "$PageDir/$id.lck";
  2717. }
  2718. sub RequestLockDir {
  2719. my ($name, $tries, $wait, $error, $retried) = @_;
  2720. $tries ||= 4;
  2721. $wait ||= 2;
  2722. CreateDir($TempDir);
  2723. my $lock = $LockDir . $name;
  2724. my $n = 0;
  2725. while (mkdir($lock, 0555) == 0) {
  2726. if ($n++ >= $tries) {
  2727. my $ts = (stat($lock))[9];
  2728. if ($Now - $ts > $LockExpiration and $LockExpires{$name} and not $retried) { # XXX should we remove this now?
  2729. ReleaseLockDir($name); # try to expire lock (no checking)
  2730. return 1 if RequestLockDir($name, undef, undef, undef, 1);
  2731. }
  2732. return 0 unless $error;
  2733. ReportError(Ts('Could not get %s lock', $name) . ": $!. ",
  2734. '503 SERVICE UNAVAILABLE', undef,
  2735. Ts('The lock was created %s.', CalcTimeSince($Now - $ts))
  2736. . ($retried && ' ' . T('Maybe the user running this script is no longer allowed to remove the lock directory?'))
  2737. . ' ' . T('Sometimes locks are left behind if a job crashes.') . ' '
  2738. . ($Now - $ts < 600 ? T('After ten minutes, you could try to unlock the wiki.')
  2739. : ScriptLink('action=unlock', T('Unlock Wiki'), 'unlock')));
  2740. }
  2741. sleep($wait);
  2742. }
  2743. $Locks{$name} = 1;
  2744. return 1;
  2745. }
  2746. sub HandleSignals {
  2747. my ($signal) = @_; # TODO should we pass it to CleanLock?
  2748. CleanLock($_) foreach keys %Locks;
  2749. exit; # let's count it as graceful exit
  2750. }
  2751. sub CleanLock {
  2752. my ($name) = @_;
  2753. $LockCleaners{$name}->() if exists $LockCleaners{$name};
  2754. ReleaseLockDir($name); # TODO should we log this?
  2755. }
  2756. sub ReleaseLockDir {
  2757. my $name = shift; # We don't check whether we succeeded.
  2758. rmdir($LockDir . $name); # Before fixing, make sure we only call this
  2759. delete $Locks{$name}; # when we know the lock exists.
  2760. }
  2761. sub RequestLockOrError {
  2762. return RequestLockDir('main', 10, 3, 1); # 10 tries, 3 second wait, die on error
  2763. }
  2764. sub ReleaseLock {
  2765. ReleaseLockDir('main');
  2766. }
  2767. sub ForceReleaseLock {
  2768. my $pattern = shift;
  2769. my $forced;
  2770. foreach my $name (bsd_glob $pattern) {
  2771. # First try to obtain lock (in case of normal edit lock)
  2772. $forced = 1 unless RequestLockDir($name, 5, 3, 0);
  2773. ReleaseLockDir($name); # Release the lock, even if we didn't get it. This should not happen.
  2774. }
  2775. return $forced;
  2776. }
  2777. sub DoUnlock {
  2778. my $message = '';
  2779. print GetHeader('', T('Unlock Wiki'), undef, 'nocache');
  2780. print $q->p(T('This operation may take several seconds...'));
  2781. for my $lock (@KnownLocks) {
  2782. if (ForceReleaseLock($lock)) {
  2783. $message .= $q->p(Ts('Forced unlock of %s lock.', $lock));
  2784. }
  2785. }
  2786. print $message || $q->p(T('No unlock required.'));
  2787. PrintFooter();
  2788. }
  2789. sub CalcDay {
  2790. my ($sec, $min, $hour, $mday, $mon, $year) = gmtime(shift);
  2791. return sprintf('%4d-%02d-%02d', $year + 1900, $mon + 1, $mday);
  2792. }
  2793. sub CalcTime {
  2794. my ($sec, $min, $hour, $mday, $mon, $year) = gmtime(shift);
  2795. return sprintf('%02d:%02d UTC', $hour, $min);
  2796. }
  2797. sub CalcTimeSince {
  2798. my $total = shift;
  2799. return Ts('%s hours ago', int($total/3600)) if ($total >= 7200);
  2800. return T('1 hour ago') if ($total >= 3600);
  2801. return Ts('%s minutes ago', int($total/60)) if ($total >= 120);
  2802. return T('1 minute ago') if ($total >= 60);
  2803. return Ts('%s seconds ago', int($total)) if ($total >= 2);
  2804. return T('1 second ago') if ($total == 1);
  2805. return T('just now');
  2806. }
  2807. sub TimeToText {
  2808. my $t = shift;
  2809. return CalcDay($t) . ' ' . CalcTime($t);
  2810. }
  2811. sub TimeToW3 { # Complete date plus hours and minutes: YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
  2812. my ($sec, $min, $hour, $mday, $mon, $year) = gmtime(shift); # use special UTC designator ("Z")
  2813. return sprintf('%4d-%02d-%02dT%02d:%02dZ', $year + 1900, $mon + 1, $mday, $hour, $min);
  2814. }
  2815. sub TimeToRFC822 {
  2816. my ($sec, $min, $hour, $mday, $mon, $year, $wday) = gmtime(shift); # Sat, 07 Sep 2002 00:00:01 GMT
  2817. return sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT", qw(Sun Mon Tue Wed Thu Fri Sat)[$wday], $mday,
  2818. qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)[$mon], $year + 1900, $hour, $min, $sec);
  2819. }
  2820. sub GetHiddenValue {
  2821. my ($name, $value) = @_;
  2822. return $q->input({-type=>"hidden", -name=>$name, -value=>$value});
  2823. }
  2824. sub FreeToNormal { # trim all spaces and convert them to underlines
  2825. my $id = shift;
  2826. return '' unless $id;
  2827. $id =~ s/ /_/g;
  2828. $id =~ s/__+/_/g;
  2829. $id =~ s/^_//;
  2830. $id =~ s/_$//;
  2831. return UnquoteHtml($id);
  2832. }
  2833. sub ItemName {
  2834. my $id = shift; # id
  2835. return NormalToFree($id) unless GetParam('short', 1) and $RssStrip;
  2836. my $comment = $id =~ s/^($CommentsPrefix)//; # strip first so that ^ works
  2837. $id =~ s/^$RssStrip//;
  2838. $id = $CommentsPrefix . $id if $comment;
  2839. return NormalToFree($id);
  2840. }
  2841. sub NormalToFree { # returns HTML quoted title with spaces
  2842. my $title = shift;
  2843. $title =~ s/_/ /g;
  2844. return QuoteHtml($title);
  2845. }
  2846. sub UnWiki {
  2847. my $str = shift;
  2848. return $str unless $WikiLinks and $str =~ /^$LinkPattern$/;
  2849. $str =~ s/([[:lower:]])([[:upper:]])/$1 $2/g;
  2850. return $str;
  2851. }
  2852. sub DoEdit {
  2853. my ($id, $newText, $preview) = @_;
  2854. UserCanEditOrDie($id);
  2855. my $upload = GetParam('upload', undef);
  2856. if ($upload and not $UploadAllowed and not UserIsAdmin()) {
  2857. ReportError(T('Only administrators can upload files.'), '403 FORBIDDEN');
  2858. }
  2859. OpenPage($id);
  2860. my ($revisionPage, $revision) = GetTextRevision(GetParam('revision', ''), 1); # maybe revision reset!
  2861. my $oldText = $preview ? $newText : $revisionPage->{text};
  2862. my $isFile = TextIsFile($oldText);
  2863. $upload //= $isFile;
  2864. if ($upload and not $UploadAllowed and not UserIsAdmin()) {
  2865. ReportError(T('Only administrators can upload files.'), '403 FORBIDDEN');
  2866. }
  2867. if ($upload) { # shortcut lots of code
  2868. $revision = '';
  2869. $preview = 0;
  2870. } elsif ($isFile) {
  2871. $oldText = '';
  2872. }
  2873. my $header;
  2874. if ($revision and not $upload) {
  2875. $header = Ts('Editing revision %s of', $revision) . ' ' . NormalToFree($id);
  2876. } else {
  2877. $header = Ts('Editing %s', NormalToFree($id));
  2878. }
  2879. print GetHeader('', $header), $q->start_div({-class=>'content edit'});
  2880. if ($preview and not $upload) {
  2881. print $q->start_div({-class=>'preview'});
  2882. print $q->h2(T('Preview:'));
  2883. PrintWikiToHTML($oldText); # no caching, current revision, unlocked
  2884. print $q->hr(), $q->h2(T('Preview only, not yet saved')), $q->end_div();
  2885. }
  2886. if ($revision) {
  2887. print $q->strong(Ts('Editing old revision %s.', $revision) . ' '
  2888. . T('Saving this page will replace the latest revision with this text.'))
  2889. }
  2890. print GetEditForm($id, $upload, $oldText, $revision), $q->end_div();
  2891. PrintFooter($id, 'edit');
  2892. }
  2893. sub GetEditForm {
  2894. my ($page_name, $upload, $oldText, $revision) = @_;
  2895. my $html = GetFormStart(undef, undef, $upload ? 'edit upload' : 'edit text') # protected by questionasker
  2896. .$q->p(GetHiddenValue("title", $page_name),
  2897. ($revision ? GetHiddenValue('revision', $revision) : ''),
  2898. GetHiddenValue('oldtime', GetParam('oldtime', $Page{ts})), # prefer parameter over actual timestamp
  2899. ($upload ? GetUpload() : GetTextArea('text', $oldText)));
  2900. my $summary = UnquoteHtml(GetParam('summary', ''))
  2901. || ($Now - $Page{ts} < ($SummaryHours * 3600) ? $Page{summary} : '');
  2902. $html .= $q->p(T('Summary:').$q->br().GetTextArea('summary', $summary, 2))
  2903. .$q->p($q->checkbox(-name=>'recent_edit', -checked=>(GetParam('recent_edit', '') eq 'on'),
  2904. -label=>T('This change is a minor edit.')));
  2905. $html .= T($EditNote) if $EditNote; # Allow translation
  2906. my $username = GetParam('username', '');
  2907. $html .= $q->p($q->label({-for=>'username'}, T('Username:')).' '
  2908. .$q->textfield(-name=>'username', -id=>'username', -default=>$username,
  2909. -override=>1, -size=>20, -maxlength=>50))
  2910. .$q->p($q->submit(-name=>'Save', -accesskey=>T('s'), -value=>T('Save')),
  2911. ($upload ? '' : ' ' . $q->submit(-name=>'Preview', -accesskey=>T('p'), -value=>T('Preview'))).
  2912. ' '.$q->submit(-name=>'Cancel', -value=>T('Cancel')));
  2913. if ($upload) {
  2914. $html .= $q->p(ScriptLink('action=edit;upload=0;id=' . UrlEncode($page_name), T('Replace this file with text'), 'upload'));
  2915. } elsif ($UploadAllowed or UserIsAdmin()) {
  2916. $html .= $q->p(ScriptLink('action=edit;upload=1;id=' . UrlEncode($page_name), T('Replace this text with a file'), 'upload'));
  2917. }
  2918. $html .= $q->end_form();
  2919. foreach my $sub (@MyFormChanges) {
  2920. $html = $sub->($html, 'edit', $upload);
  2921. }
  2922. return $html;
  2923. }
  2924. sub GetTextArea {
  2925. my ($name, $text, $rows) = @_;
  2926. return $q->textarea(-id=>$name, -name=>$name, -default=>$text, -rows=>$rows || 25, -columns=>78, -override=>1);
  2927. }
  2928. sub GetUpload {
  2929. return T('File to upload:') . ' ' . $q->filefield(-name=>'file', -size=>50, -maxlength=>100);
  2930. }
  2931. sub DoDownload {
  2932. my $id = shift;
  2933. OpenPage($id) if ValidIdOrDie($id);
  2934. print $q->header(-status=>'304 NOT MODIFIED') and return if FileFresh(); # FileFresh needs an OpenPage!
  2935. my ($revisionPage, $revision) = GetTextRevision(GetParam('revision', '')); # maybe revision reset!
  2936. my $text = $revisionPage->{text};
  2937. if (my ($type, $encoding) = TextIsFile($text)) {
  2938. my ($data) = $text =~ /^[^\n]*\n(.*)/s;
  2939. my %allowed = map {$_ => 1} @UploadTypes;
  2940. if (@UploadTypes and not $allowed{$type}) {
  2941. ReportError(Ts('Files of type %s are not allowed.', $type), '415 UNSUPPORTED MEDIA TYPE');
  2942. }
  2943. print GetHttpHeader($type, $Page{ts}, undef, $encoding);
  2944. require MIME::Base64;
  2945. binmode(STDOUT, ":pop:raw"); # need to pop utf8 for Windows users!?
  2946. print MIME::Base64::decode($data);
  2947. } else {
  2948. print GetHttpHeader('text/plain', $Page{ts});
  2949. print $text;
  2950. }
  2951. }
  2952. sub DoPassword {
  2953. my $id = shift;
  2954. print GetHeader('', T('Password')), $q->start_div({-class=>'content password'});
  2955. print $q->p(T('Your password is saved in a cookie, if you have cookies enabled. Cookies may get lost if you connect from another machine, from another account, or using another software.'));
  2956. if (not $AdminPass and not $EditPass) {
  2957. print $q->p(T('This site does not use admin or editor passwords.'));
  2958. } else {
  2959. if (UserIsAdmin()) {
  2960. print $q->p(T('You are currently an administrator on this site.'));
  2961. } elsif (UserIsEditor()) {
  2962. print $q->p(T('You are currently an editor on this site.'));
  2963. } else {
  2964. print $q->p(T('You are a normal user on this site.'));
  2965. if (not GetParam('pwd')) {
  2966. print $q->p(T('You do not have a password set.'));
  2967. } else {
  2968. print $q->p(T('Your password does not match any of the administrator or editor passwords.'));
  2969. }
  2970. }
  2971. print GetFormStart(undef, undef, 'password'),
  2972. $q->p(GetHiddenValue('action', 'password'), T('Password:'), ' ',
  2973. $q->password_field(-name=>'pwd', -size=>20, -maxlength=>64),
  2974. $q->hidden(-name=>'id', -value=>$id),
  2975. $q->submit(-name=>'Save', -accesskey=>T('s'), -value=>T('Save'))),
  2976. $q->end_form;
  2977. }
  2978. if ($id) {
  2979. print $q->p(ScriptLink('action=browse;id=' . UrlEncode($id) . ';time=' . time,
  2980. Ts('Return to %s', NormalToFree($id))));
  2981. }
  2982. print $q->end_div();
  2983. PrintFooter();
  2984. }
  2985. sub UserIsEditorOrError {
  2986. UserIsEditor()
  2987. or ReportError(T('This operation is restricted to site editors only...'), '403 FORBIDDEN');
  2988. return 1;
  2989. }
  2990. sub UserIsAdminOrError {
  2991. UserIsAdmin()
  2992. or ReportError(T('This operation is restricted to administrators only...'), '403 FORBIDDEN');
  2993. return 1;
  2994. }
  2995. sub UserCanEditOrDie {
  2996. my $id = shift;
  2997. ValidIdOrDie($id);
  2998. if (not UserCanEdit($id, 1)) {
  2999. my $rule = UserIsBanned();
  3000. if ($rule) {
  3001. ReportError(T('Edit Denied'), '403 FORBIDDEN', undef,
  3002. $q->p(T('Editing not allowed: user, ip, or network is blocked.')),
  3003. $q->p(T('Contact the wiki administrator for more information.')),
  3004. $q->p(Ts('The rule %s matched for you.', $rule) . ' '
  3005. . Ts('See %s for more information.', GetPageLink($BannedHosts))));
  3006. } else {
  3007. ReportError(T('Edit Denied'), '403 FORBIDDEN', undef,
  3008. $q->p(Ts('Editing not allowed: %s is read-only.', NormalToFree($id))));
  3009. }
  3010. }
  3011. }
  3012. sub UserCanEdit {
  3013. my ($id, $editing, $comment) = @_;
  3014. return 0 if $id eq 'SampleUndefinedPage' or $id eq T('SampleUndefinedPage')
  3015. or $id eq 'Sample_Undefined_Page' or $id eq T('Sample_Undefined_Page');
  3016. return 1 if UserIsAdmin();
  3017. return 0 if $id ne '' and -f GetLockedPageFile($id);
  3018. return 0 if $LockOnCreation{$id} and not -f GetPageFile($id); # new page
  3019. return 1 if UserIsEditor();
  3020. return 0 if not $EditAllowed or -f $NoEditFile;
  3021. return 0 if $editing and UserIsBanned(); # this call is more expensive
  3022. return 0 if $EditAllowed >= 2 and (not $CommentsPattern or $id !~ /$CommentsPattern/);
  3023. return 1 if $EditAllowed >= 3 and GetParam('recent_edit', '') ne 'on' # disallow minor comments
  3024. and ($comment or (GetParam('aftertext', '') and not GetParam('text', '')));
  3025. return 0 if $EditAllowed >= 3;
  3026. return 1;
  3027. }
  3028. sub UserIsBanned {
  3029. return 0 if GetParam('action', '') eq 'password'; # login is always ok
  3030. my $host = $q->remote_addr();
  3031. foreach (split(/\n/, GetPageContent($BannedHosts))) {
  3032. if (/^\s*([^#]\S+)/) { # all lines except empty lines and comments, trim whitespace
  3033. my $regexp = $1;
  3034. return $regexp if ($host =~ /$regexp/i);
  3035. }
  3036. }
  3037. return 0;
  3038. }
  3039. sub UserIsAdmin {
  3040. return UserHasPassword(GetParam('pwd', ''), $AdminPass);
  3041. }
  3042. sub UserIsEditor {
  3043. return 1 if UserIsAdmin(); # Admin includes editor
  3044. return UserHasPassword(GetParam('pwd', ''), $EditPass);
  3045. }
  3046. sub UserHasPassword {
  3047. my ($pwd, $pass) = @_;
  3048. return 0 unless $pass;
  3049. if ($PassHashFunction ne '') {
  3050. no strict 'refs'; # TODO this is kept for compatibility. Feel free to remove it later (comment written on 2015-07-14)
  3051. $pwd = $PassHashFunction->($pwd . $PassSalt);
  3052. }
  3053. foreach (split(/\s+/, $pass)) {
  3054. return 1 if $pwd eq $_;
  3055. }
  3056. return 0;
  3057. }
  3058. sub BannedContent {
  3059. my $str = shift;
  3060. my @urls = $str =~ /$FullUrlPattern/g;
  3061. foreach (split(/\n/, GetPageContent($BannedContent))) {
  3062. next unless m/^\s*([^#]+?)\s*(#\s*(\d\d\d\d-\d\d-\d\d\s*)?(.*))?$/;
  3063. my ($regexp, $comment, $re) = ($1, $4, undef);
  3064. foreach my $url (@urls) {
  3065. eval { $re = qr/$regexp/i; };
  3066. if (defined($re) and $url =~ $re) {
  3067. return Tss('Rule "%1" matched "%2" on this page.', $regexp, $url) . ' '
  3068. . ($comment ? Ts('Reason: %s.', $comment) : T('Reason unknown.')) . ' '
  3069. . Ts('See %s for more information.', GetPageLink($BannedContent));
  3070. }
  3071. }
  3072. }
  3073. return 0;
  3074. }
  3075. sub SortIndex {
  3076. my ($A, $B) = ($a, $b);
  3077. my $aIsComment = $A =~ s/^$CommentsPrefix//;
  3078. $B =~ s/^$CommentsPrefix//;
  3079. return $aIsComment ? 1 : -1 if $A eq $B;
  3080. $A cmp $B;
  3081. }
  3082. sub DoIndex {
  3083. my $raw = GetParam('raw', 0);
  3084. my $match = GetParam('match', '');
  3085. my @pages = ();
  3086. my @menu = ($q->label({-for=>'indexmatch'}, T('Filter:')) . ' '
  3087. . $q->textfield(-name=>'match', -id=>'indexmatch', -size=>20));
  3088. foreach my $data (@IndexOptions) {
  3089. my ($option, $text, $default, $sub) = @$data;
  3090. my $value = GetParam($option, $default); # HTML checkbox warning!
  3091. $value = 0 if GetParam('manual', 0) and $value ne 'on';
  3092. push(@pages, $sub->()) if $value;
  3093. push(@menu, $q->checkbox(-name=>$option, -checked=>$value, -label=>$text));
  3094. }
  3095. @pages = grep /$match/i, @pages if $match;
  3096. @pages = sort SortIndex @pages;
  3097. if ($raw) {
  3098. print GetHttpHeader('text/plain'); # and ignore @menu
  3099. } else {
  3100. print GetHeader('', T('Index of all pages'));
  3101. push(@menu, GetHiddenValue('manual', 1) . $q->submit(-value=>T('Go!')));
  3102. push(@menu, $q->b(Ts('(for %s)', GetParam('lang', '')))) if GetParam('lang', '');
  3103. print $q->start_div({-class=>'content index'}),
  3104. GetFormStart(undef, 'get', 'index'), GetHiddenValue('action', 'index'),
  3105. $q->p(join($q->br(), @menu)), $q->end_form(),
  3106. $q->h2(Ts('%s pages found.', ($#pages + 1))), $q->start_p();
  3107. }
  3108. PrintPage($_) foreach (@pages);
  3109. print $q->end_p(), $q->end_div() unless $raw;
  3110. PrintFooter() unless $raw;
  3111. }
  3112. sub PrintPage {
  3113. my $id = shift;
  3114. my $lang = GetParam('lang', 0);
  3115. if ($lang) {
  3116. OpenPage($id);
  3117. my @languages = split(/,/, $Page{languages});
  3118. next if (@languages and not grep(/$lang/, @languages));
  3119. }
  3120. if (GetParam('raw', 0)) {
  3121. if (GetParam('search', '') and GetParam('context', 1)) {
  3122. print "title: $id\n\n"; # for near links without full search
  3123. } else {
  3124. print $id, "\n";
  3125. }
  3126. } else {
  3127. print GetPageOrEditLink($id, NormalToFree($id)), $q->br();
  3128. }
  3129. }
  3130. sub AllPagesList {
  3131. my $refresh = GetParam('refresh', 0);
  3132. return @IndexList if @IndexList and not $refresh;
  3133. SetParam('refresh', 0) if $refresh;
  3134. return @IndexList if not $refresh and -f $IndexFile and ReadIndex();
  3135. # If open fails just refresh the index
  3136. RefreshIndex();
  3137. return @IndexList;
  3138. }
  3139. sub ReadIndex {
  3140. my ($status, $rawIndex) = ReadFile($IndexFile); # not fatal
  3141. if ($status) {
  3142. @IndexList = split(/ /, $rawIndex);
  3143. %IndexHash = map {$_ => 1} @IndexList;
  3144. return @IndexList;
  3145. }
  3146. return;
  3147. }
  3148. sub WriteIndex {
  3149. WriteStringToFile($IndexFile, join(' ', @IndexList));
  3150. }
  3151. sub RefreshIndex {
  3152. @IndexList = ();
  3153. %IndexHash = ();
  3154. # If file exists and cannot be changed, error!
  3155. my $locked = RequestLockDir('index', undef, undef, -f $IndexFile);
  3156. foreach (bsd_glob("$PageDir/*.pg"), bsd_glob("$PageDir/.*.pg")) {
  3157. next unless m|/.*/(.+)\.pg$|;
  3158. my $id = $1;
  3159. utf8::decode($id);
  3160. push(@IndexList, $id);
  3161. $IndexHash{$id} = 1;
  3162. }
  3163. WriteIndex() if $locked;
  3164. ReleaseLockDir('index') if $locked;
  3165. }
  3166. sub AddToIndex {
  3167. my ($id) = @_;
  3168. $IndexHash{$id} = 1;
  3169. @IndexList = sort(keys %IndexHash);
  3170. WriteIndex();
  3171. }
  3172. sub DoSearch {
  3173. my $string = shift || GetParam('search', '');
  3174. my $re = UnquoteHtml($string);
  3175. return DoIndex() if $string eq '';
  3176. eval { qr/$re/ } or $re = quotemeta($re);
  3177. my $replacement = GetParam('replace', undef);
  3178. my $raw = GetParam('raw', '');
  3179. my @results;
  3180. if ($replacement or GetParam('delete', 0)) {
  3181. return unless UserIsAdminOrError();
  3182. if (GetParam('preview', '')) { # Preview button was used
  3183. print GetHeader('', Ts('Preview: %s', $string . " &#x2192; " . $replacement));
  3184. print $q->start_div({-class=>'content replacement'});
  3185. print GetFormStart(undef, 'post', 'replace');
  3186. print GetHiddenValue('search', $string);
  3187. print GetHiddenValue('replace', $replacement);
  3188. print GetHiddenValue('delete', GetParam('delete', 0));
  3189. print $q->submit(-value=>T('Go!')) . $q->end_form();
  3190. @results = ReplaceAndDiff($re, UnquoteHtml($replacement));
  3191. } else {
  3192. print GetHeader('', Ts('Replaced: %s', $string . " &#x2192; " . $replacement));
  3193. print $q->start_div({-class=>'content replacement'});
  3194. @results = ReplaceAndSave($re, UnquoteHtml($replacement));
  3195. foreach (@results) {
  3196. PrintSearchResult($_, quotemeta($replacement || $re)); # the replacement is not a valid regex
  3197. }
  3198. }
  3199. } else {
  3200. if ($raw) {
  3201. print GetHttpHeader('text/plain');
  3202. print RcTextItem('title', Ts('Search for: %s', $string)), RcTextItem('date', TimeToText($Now)),
  3203. RcTextItem('link', $q->url(-path_info=>1, -query=>1)), "\n" if GetParam('context', 1);
  3204. } else {
  3205. print GetHeader('', Ts('Search for: %s', $string)), $q->start_div({-class=>'content search'});
  3206. print $q->p({-class=>'links'}, SearchMenu($string));
  3207. }
  3208. @results = SearchTitleAndBody($re, \&PrintSearchResult, SearchRegexp($re));
  3209. }
  3210. print SearchResultCount($#results + 1), $q->end_div() unless $raw;
  3211. PrintFooter() unless $raw;
  3212. }
  3213. sub SearchMenu {
  3214. return ScriptLink('action=rc;rcfilteronly=' . UrlEncode(shift),
  3215. T('View changes for these pages'));
  3216. }
  3217. sub SearchResultCount { $q->p({-class=>'result'}, Ts('%s pages found.', (shift))); }
  3218. sub PageIsUploadedFile {
  3219. my $id = shift;
  3220. return if $OpenPageName eq $id;
  3221. if ($IndexHash{$id}) {
  3222. my $file = GetPageFile($id);
  3223. utf8::encode($file); # filenames are bytes!
  3224. open(my $FILE, '<:encoding(UTF-8)', $file)
  3225. or ReportError(Ts('Cannot open %s', $file) . ": $!", '500 INTERNAL SERVER ERROR');
  3226. while (defined($_ = <$FILE>) and $_ !~ /^text: /) {
  3227. } # read lines until we get to the text key
  3228. close $FILE;
  3229. return TextIsFile(substr($_, 6)); # pass "#FILE image/png\n" to the test
  3230. }
  3231. }
  3232. sub SearchTitleAndBody {
  3233. my ($regex, $func, @args) = @_;
  3234. my @found;
  3235. my $lang = GetParam('lang', '');
  3236. foreach my $id (Filtered($regex, AllPagesList())) {
  3237. my $name = NormalToFree($id);
  3238. my ($text) = PageIsUploadedFile($id); # set to mime-type if this is an uploaded file
  3239. if (not $text) { # not uploaded file, therefore allow searching of page body
  3240. local ($OpenPageName, %Page); # this is local!
  3241. OpenPage($id); # this opens a page twice if it is not uploaded, but that's ok
  3242. if ($lang) {
  3243. my @languages = split(/,/, $Page{languages});
  3244. next if (@languages and not grep(/$lang/, @languages));
  3245. }
  3246. $text = $Page{text};
  3247. }
  3248. if (SearchString($regex, $name . "\n" . $text)) { # the real search code
  3249. push(@found, $id);
  3250. $func->($id, @args) if $func;
  3251. }
  3252. }
  3253. return @found;
  3254. }
  3255. sub Filtered { # this is overwriten in extensions such as tags.pl
  3256. return @_[1 .. $#_]; # ignores $regex and returns all pages
  3257. }
  3258. sub SearchString {
  3259. my ($string, $data) = @_;
  3260. my @strings = grep /./, $string =~ /\"([^\"]+)\"|(\S+)/g; # skip null entries
  3261. foreach my $str (@strings) {
  3262. return 0 unless ($data =~ /$str/i);
  3263. }
  3264. return 1;
  3265. }
  3266. sub SearchRegexp {
  3267. my $regexp = join '|', map { index($_, '|') == -1 ? $_ : "($_)" }
  3268. grep /./, shift =~ /\"([^\"]+)\"|(\S+)/g; # this acts as OR
  3269. $regexp =~ s/\\s/[[:space:]]/g;
  3270. return $regexp;
  3271. }
  3272. sub PrintSearchResult {
  3273. my ($name, $regex) = @_;
  3274. return PrintPage($name) if not GetParam('context', 1);
  3275. OpenPage($name); # should be open already, just making sure!
  3276. my $text = $Page{text};
  3277. my ($type) = TextIsFile($text); # MIME type if an uploaded file
  3278. my %entry;
  3279. # get the page, filter it, remove all tags
  3280. $text =~ s/$FS//g; # Remove separators (paranoia)
  3281. $text =~ s/[\s]+/ /g; # Shrink whitespace
  3282. $text =~ s/([-_=\\*\\.]){10,}/$1$1$1$1$1/g ; # e.g. shrink "----------"
  3283. $entry{title} = $name;
  3284. $entry{description} = $type || SearchHighlight(QuoteHtml(SearchExtract($text, $regex)), QuoteHtml($regex));
  3285. $entry{size} = int((length($text) / 1024) + 1) . 'K';
  3286. $entry{'last-modified'} = TimeToText($Page{ts});
  3287. $entry{username} = $Page{username};
  3288. $entry{host} = $Page{host};
  3289. PrintSearchResultEntry(\%entry);
  3290. }
  3291. sub PrintSearchResultEntry {
  3292. my %entry = %{(shift)}; # get value from reference
  3293. if (GetParam('raw', 0)) {
  3294. $entry{generator} = GetAuthor($entry{host}, $entry{username});
  3295. foreach my $key (qw(title description size last-modified generator username host)) {
  3296. print RcTextItem($key, $entry{$key});
  3297. }
  3298. print RcTextItem('link', "$ScriptName?$entry{title}"), "\n";
  3299. } else {
  3300. my $author = GetAuthorLink($entry{host}, $entry{username});
  3301. $author ||= $entry{generator};
  3302. my $id = $entry{title};
  3303. my ($class, $resolved, $title, $exists) = ResolveId($id);
  3304. my $text = NormalToFree($id);
  3305. my $result = $q->span({-class=>'result'}, ScriptLink(UrlEncode($resolved), $text, $class, undef, $title));
  3306. my $description = $entry{description};
  3307. $description = $q->br() . $description if $description;
  3308. my $info = $entry{size};
  3309. $info .= ' - ' if $info;
  3310. $info .= T('last updated') . ' ' . $entry{'last-modified'} if $entry{'last-modified'};
  3311. $info .= ' ' . T('by') . ' ' . $author if $author;
  3312. $info = $q->br() . $q->span({-class=>'info'}, $info) if $info;
  3313. print $q->p($result, $description, $info);
  3314. }
  3315. }
  3316. sub SearchHighlight {
  3317. my ($data, $regex) = @_;
  3318. $data =~ s/($regex)/<strong>$1<\/strong>/gi unless GetParam('raw');
  3319. return $data;
  3320. }
  3321. sub SearchExtract {
  3322. my ($data, $regex) = @_;
  3323. my ($snippetlen, $maxsnippets) = (100, 4); # these seem nice.
  3324. # show a snippet from the beginning of the document
  3325. my $j = index($data, ' ', $snippetlen); # end on word boundary
  3326. my $t = substr($data, 0, $j);
  3327. my $result = $t . ' . . .';
  3328. $data = substr($data, $j); # to avoid rematching
  3329. my $jsnippet = 0 ;
  3330. while ($jsnippet < $maxsnippets and $data =~ m/($regex)/i) {
  3331. $jsnippet++;
  3332. if (($j = index($data, $1)) > -1 ) {
  3333. # get substr containing (start of) match, ending on word boundaries
  3334. my $start = index($data, ' ', $j - $snippetlen / 2);
  3335. $start = 0 if $start == -1;
  3336. my $end = index($data, ' ', $j + $snippetlen / 2);
  3337. $end = length($data) if $end == -1;
  3338. $t = substr($data, $start, $end - $start);
  3339. $result .= $t . ' . . .';
  3340. # truncate text to avoid rematching the same string.
  3341. $data = substr($data, $end);
  3342. }
  3343. }
  3344. return $result;
  3345. }
  3346. sub ReplaceAndSave {
  3347. my ($from, $to) = @_;
  3348. RequestLockOrError(); # fatal
  3349. my @result = Replace($from, $to, 1, sub {
  3350. my ($id, $new) = @_;
  3351. Save($id, $new, $from . ' → ' . $to, 1, ($Page{host} ne $q->remote_addr()));
  3352. });
  3353. ReleaseLock();
  3354. return @result;
  3355. }
  3356. sub ReplaceAndDiff {
  3357. my ($from, $to) = @_;
  3358. my @found = Replace($from, $to, 0, sub {
  3359. my ($id, $new) = @_;
  3360. print $q->h2(GetPageLink($id)), $q->div({-class=>'diff'}, ImproveDiff(DoDiff($Page{text}, $new)));
  3361. });
  3362. if (@found > GetParam('offset', 0) + GetParam('num', 10)) {
  3363. my $more = "search=" . UrlEncode($from) . ";preview=1"
  3364. . ";offset=" . (GetParam('num', 10) + GetParam('offset', 0))
  3365. . ";num=" . GetParam('num', 10);
  3366. $more .= ";replace=" . UrlEncode($to) if $to;
  3367. $more .= ";delete=1" unless $to;
  3368. print $q->p({-class=>'more'}, ScriptLink($more, T('More...'), 'more'));
  3369. }
  3370. return @found;
  3371. }
  3372. sub Replace {
  3373. my ($from, $to, $all, $func) = @_; # $func takes $id and $new text
  3374. my $lang = GetParam('lang', '');
  3375. my $num = GetParam('num', 10);
  3376. my $offset = GetParam('offset', 0);
  3377. my @result;
  3378. foreach my $id (AllPagesList()) {
  3379. OpenPage($id);
  3380. if ($lang) {
  3381. my @languages = split(/,/, $Page{languages});
  3382. next if (@languages and not grep(/$lang/, @languages));
  3383. }
  3384. $_ = $Page{text};
  3385. my $replacement = sub {
  3386. my ($o1, $o2, $o3, $o4, $o5, $o6, $o7, $o8, $o9) = ($1, $2, $3, $4, $5, $6, $7, $8, $9);
  3387. my $str = $to;
  3388. $str =~ s/\$([1-9])/'$o' . $1/eeg;
  3389. $str
  3390. };
  3391. if (s/$from/$replacement->()/egi) { # allows use of backreferences
  3392. push (@result, $id);
  3393. $func->($id, $_) if $all or @result > $offset and @result <= $offset + $num;
  3394. }
  3395. }
  3396. return @result;
  3397. }
  3398. sub DoPost {
  3399. my $id = FreeToNormal(shift);
  3400. UserCanEditOrDie($id);
  3401. # Lock before getting old page to prevent races
  3402. RequestLockOrError(); # fatal
  3403. OpenPage($id);
  3404. my $old = $Page{text};
  3405. my $string = UnquoteHtml(GetParam('text', undef));
  3406. $string =~ s/(\r|$FS)//g;
  3407. my ($type) = TextIsFile($string); # MIME type if an uploaded file
  3408. my $filename = GetParam('file', undef);
  3409. if (($filename or $type) and not $UploadAllowed and not UserIsAdmin()) {
  3410. ReportError(T('Only administrators can upload files.'), '403 FORBIDDEN');
  3411. }
  3412. my $comment = UnquoteHtml(GetParam('aftertext', undef));
  3413. $comment =~ s/(\r|$FS)//g;
  3414. if (defined $comment and $comment eq '') {
  3415. ReleaseLock();
  3416. return ReBrowsePage($id);
  3417. }
  3418. if ($filename) { # upload file
  3419. my $file = $q->upload('file');
  3420. if (not $file and $q->cgi_error) {
  3421. ReportError(Ts('Transfer Error: %s', $q->cgi_error), '500 INTERNAL SERVER ERROR');
  3422. }
  3423. ReportError(T('Browser reports no file info.'), '500 INTERNAL SERVER ERROR') unless $q->uploadInfo($filename);
  3424. $type = $q->uploadInfo($filename)->{'Content-Type'};
  3425. ReportError(T('Browser reports no file type.'), '415 UNSUPPORTED MEDIA TYPE') unless $type;
  3426. local $/ = undef; # Read complete files
  3427. my $content = <$file>; # Apparently we cannot count on <$file> to always work within the eval!?
  3428. my $encoding = substr($content, 0, 2) eq "\x1f\x8b" ? 'gzip' : '';
  3429. eval { require MIME::Base64; $_ = MIME::Base64::encode($content) };
  3430. $string = "#FILE $type $encoding\n" . $_;
  3431. } else { # ordinary text edit
  3432. $string = AddComment($old, $comment) if defined $comment;
  3433. if ($comment and substr($string, 0, length($DeletedPage)) eq $DeletedPage) { # look ma, no regexp!
  3434. $string = substr($string, length($DeletedPage)); # undelete pages when adding a comment
  3435. }
  3436. $string .= "\n" if ($string !~ /\n$/); # add trailing newline
  3437. $string = RunMyMacros($string); # run macros on text pages only
  3438. }
  3439. my %allowed = map {$_ => 1} @UploadTypes;
  3440. if (@UploadTypes and $type and not $allowed{$type}) {
  3441. ReportError(Ts('Files of type %s are not allowed.', $type), '415 UNSUPPORTED MEDIA TYPE');
  3442. }
  3443. # Banned Content
  3444. my $summary = GetSummary();
  3445. if (not UserIsEditor()) {
  3446. my $rule = BannedContent($string) || BannedContent($summary);
  3447. ReportError(T('Edit Denied'), '403 FORBIDDEN', undef, $q->p(T('The page contains banned text.')),
  3448. $q->p(T('Contact the wiki administrator for more information.')), $q->p($rule)) if $rule;
  3449. }
  3450. # rebrowse if no changes
  3451. my $oldrev = $Page{revision};
  3452. if (GetParam('Preview', '')) { # Preview button was used
  3453. ReleaseLock();
  3454. if (defined $comment) {
  3455. BrowsePage($id, 0, RunMyMacros($comment)); # show macros in preview
  3456. } else {
  3457. DoEdit($id, $string, 1);
  3458. }
  3459. return;
  3460. } elsif ($old eq $string) {
  3461. ReleaseLock(); # No changes -- just show the same page again
  3462. return ReBrowsePage($id);
  3463. } elsif ($oldrev == 0 and $string eq "\n") {
  3464. ReportError(T('No changes to be saved.'), '400 BAD REQUEST'); # don't fake page creation because of webdav
  3465. }
  3466. my $newAuthor = 0;
  3467. if ($oldrev) { # the first author (no old revision) is not considered to be "new"
  3468. # prefer usernames for potential new author detection
  3469. $newAuthor = 1 if not $Page{username} or $Page{username} ne GetParam('username', '');
  3470. $newAuthor = 1 if not $q->remote_addr() or not $Page{host} or $q->remote_addr() ne $Page{host};
  3471. }
  3472. my $oldtime = $Page{ts};
  3473. my $myoldtime = GetParam('oldtime', ''); # maybe empty!
  3474. # Handle raw edits with the meta info on the first line
  3475. if (GetParam('raw', 0) == 2 and $string =~ /^([0-9]+).*\n((.*\n)*.*)/) {
  3476. $myoldtime = $1;
  3477. $string = $2;
  3478. }
  3479. my $generalwarning = 0;
  3480. if ($newAuthor and $oldtime ne $myoldtime and not defined $comment) {
  3481. if ($myoldtime) {
  3482. my ($ancestor) = GetTextAtTime($myoldtime);
  3483. if ($ancestor and $old ne $ancestor) {
  3484. my $new = MergeRevisions($string, $ancestor, $old);
  3485. if ($new) {
  3486. $string = $new;
  3487. if ($new =~ /^<<<<<<</m and $new =~ /^>>>>>>>/m) {
  3488. SetParam('msg', Ts('This page was changed by somebody else %s.',
  3489. CalcTimeSince($Now - $Page{ts}))
  3490. . ' ' . T('The changes conflict. Please check the page again.'));
  3491. } # else no conflict
  3492. } else {
  3493. $generalwarning = 1;
  3494. } # else merge revision didn't work
  3495. } # else nobody changed the page in the mean time (same text)
  3496. } else {
  3497. $generalwarning = 1;
  3498. } # no way to be sure since myoldtime is missing
  3499. } # same author or nobody changed the page in the mean time (same timestamp)
  3500. if ($generalwarning and ($Now - $Page{ts}) < 600) {
  3501. SetParam('msg', Ts('This page was changed by somebody else %s.',
  3502. CalcTimeSince($Now - $Page{ts}))
  3503. . ' ' . T('Please check whether you overwrote those changes.'));
  3504. }
  3505. Save($id, $string, $summary, (GetParam('recent_edit', '') eq 'on'), $filename);
  3506. ReleaseLock();
  3507. ReBrowsePage($id);
  3508. }
  3509. sub GetSummary {
  3510. my $text = GetParam('aftertext', '') || ($Page{revision} > 0 ? '' : GetParam('text', ''));
  3511. return '' if $text =~ /^#FILE /;
  3512. if ($SummaryDefaultLength and length($text) > $SummaryDefaultLength) {
  3513. $text = substr($text, 0, $SummaryDefaultLength);
  3514. $text =~ s/\s*\S*$/ . . ./;
  3515. }
  3516. my $summary = GetParam('summary', '') || $text; # not GetParam('summary', $text) work because '' is defined
  3517. $summary =~ s/$FS|[\r\n]+/ /g; # remove linebreaks and separator characters
  3518. $summary =~ s/\[$FullUrlPattern\s+(.*?)\]/$2/g; # fix common annoyance when copying text to summary
  3519. $summary =~ s/\[$FullUrlPattern\]//g;
  3520. $summary =~ s/\[\[$FreeLinkPattern\]\]/$1/g;
  3521. return UnquoteHtml($summary);
  3522. }
  3523. sub AddComment {
  3524. my ($string, $comment) = @_;
  3525. $comment =~ s/\r//g; # Remove "\r"-s (0x0d) from the string
  3526. $comment =~ s/\s+$//g; # Remove whitespace at the end
  3527. if ($comment ne '') {
  3528. my $author = GetParam('username', T('Anonymous'));
  3529. my $homepage = GetParam('homepage', '');
  3530. $homepage = 'http://' . $homepage if $homepage and $homepage !~ /^($UrlProtocols):/;
  3531. $author = "[$homepage $author]" if $homepage;
  3532. $string .= "\n----\n\n" if $string and $string ne "\n";
  3533. $string .= $comment . "\n\n"
  3534. . '-- ' . $author . ' ' . TimeToText($Now) . "\n\n";
  3535. }
  3536. return $string;
  3537. }
  3538. sub Save { # call within lock, with opened page
  3539. my ($id, $new, $summary, $minor, $upload) = @_;
  3540. my $user = GetParam('username', '');
  3541. my $host = $q->remote_addr();
  3542. my $revision = $Page{revision} + 1;
  3543. my $old = $Page{text};
  3544. my $olddiff = $Page{'diff-major'} == '1' ? $Page{'diff-minor'} : $Page{'diff-major'};
  3545. if ($revision == 1 and -e $IndexFile and not unlink($IndexFile)) { # regenerate index on next request
  3546. SetParam('msg', Ts('Cannot delete the index file %s.', $IndexFile)
  3547. . ' ' . T('Please check the directory permissions.')
  3548. . ' ' . T('Your changes were not saved.'));
  3549. return 0;
  3550. }
  3551. ReInit($id);
  3552. TouchIndexFile();
  3553. SaveKeepFile(); # deletes blocks, flags, diff-major, and diff-minor, and sets keep-ts
  3554. ExpireKeepFiles();
  3555. $Page{lastmajor} = $revision unless $minor;
  3556. $Page{lastmajorsummary} = $summary unless $minor;
  3557. @Page{qw(ts revision summary username host minor text)} =
  3558. ($Now, $revision, $summary, $user, $host, $minor, $new);
  3559. if ($UseDiff and $UseCache > 1 and $revision > 1 and not $upload and not TextIsFile($old)) {
  3560. UpdateDiffs($old, $new, $olddiff); # sets diff-major and diff-minor
  3561. }
  3562. my $languages;
  3563. $languages = GetLanguages($new) unless $upload;
  3564. $Page{languages} = $languages;
  3565. SavePage();
  3566. if ($revision == 1 and $LockOnCreation{$id}) {
  3567. WriteStringToFile(GetLockedPageFile($id), 'LockOnCreation');
  3568. }
  3569. WriteRcLog($id, $summary, $minor, $revision, $user, $host, $languages, GetCluster($new));
  3570. AddToIndex($id) if ($revision == 1);
  3571. }
  3572. sub TouchIndexFile {
  3573. my $ts = time;
  3574. utime $ts, $ts, $IndexFile;
  3575. $LastUpdate = $Now = $ts;
  3576. }
  3577. sub GetLanguages {
  3578. my $text = shift;
  3579. my @result;
  3580. for my $lang (sort keys %Languages) {
  3581. my @matches = $text =~ /$Languages{$lang}/gi;
  3582. push(@result, $lang) if $#matches >= $LanguageLimit;
  3583. }
  3584. return join(',', @result);
  3585. }
  3586. sub GetCluster {
  3587. $_ = shift;
  3588. return '' unless $PageCluster;
  3589. return $1 if ($WikiLinks && /^$LinkPattern\n/)
  3590. or ($FreeLinks && /^\[\[$FreeLinkPattern\]\]\n/);
  3591. }
  3592. sub MergeRevisions { # merge change from file2 to file3 into file1
  3593. my ($file1, $file2, $file3) = @_;
  3594. my ($name1, $name2, $name3) = ("$TempDir/file1", "$TempDir/file2", "$TempDir/file3");
  3595. CreateDir($TempDir);
  3596. RequestLockDir('merge') or return T('Could not get a lock to merge!');
  3597. WriteStringToFile($name1, $file1);
  3598. WriteStringToFile($name2, $file2);
  3599. WriteStringToFile($name3, $file3);
  3600. my ($you, $ancestor, $other) = (T('you'), T('ancestor'), T('other'));
  3601. my $output = `diff3 -m -L \Q$you\E -L \Q$ancestor\E -L \Q$other\E -- \Q$name1\E \Q$name2\E \Q$name3\E`;
  3602. utf8::decode($output); # needs decoding
  3603. ReleaseLockDir('merge'); # don't unlink temp files--next merge will just overwrite.
  3604. return $output;
  3605. }
  3606. # Note: all diff and recent-list operations should be done within locks.
  3607. sub WriteRcLog {
  3608. my ($id, $summary, $minor, $revision, $username, $host, $languages, $cluster) = @_;
  3609. my $line = join($FS, $Now, $id, $minor, $summary, $host,
  3610. $username, $revision, $languages, $cluster);
  3611. AppendStringToFile($RcFile, $line . "\n");
  3612. }
  3613. sub UpdateDiffs { # this could be optimized, but isn't frequent enough
  3614. my ($old, $new, $olddiff) = @_;
  3615. $Page{'diff-minor'} = GetDiff($old, $new); # create new diff-minor
  3616. # 1 is a special value for GetCacheDiff telling it to use diff-minor
  3617. $Page{'diff-major'} = $Page{lastmajor} == $Page{revision} ? 1 : $olddiff;
  3618. }
  3619. sub DoMaintain {
  3620. print GetHeader('', T('Run Maintenance')), $q->start_div({-class=>'content maintain'});
  3621. my $fname = "$DataDir/maintain";
  3622. if (not UserIsAdmin()) {
  3623. if ((-f $fname) and ((-M $fname) < 0.5)) {
  3624. print $q->p(T('Maintenance not done.') . ' ' . T('(Maintenance can only be done once every 12 hours.)')
  3625. . ' ', T('Remove the "maintain" file or wait.')), $q->end_div();
  3626. PrintFooter();
  3627. return;
  3628. }
  3629. }
  3630. print '<p>', T('Expiring keep files and deleting pages marked for deletion');
  3631. ExpireAllKeepFiles();
  3632. print '</p>';
  3633. RequestLockOrError();
  3634. print $q->p(T('Main lock obtained.'));
  3635. print $q->p(Ts('Moving part of the %s log file.', $RCName));
  3636. # Determine the number of days to go back
  3637. my $days = 0;
  3638. foreach (@RcDays) {
  3639. $days = $_ if $_ > $days;
  3640. }
  3641. my $starttime = $Now - $days * 86400; # 24*60*60
  3642. # Read the current file
  3643. my ($status, $data) = ReadFile($RcFile);
  3644. if (not $status) {
  3645. print $q->p($q->strong(Ts('Could not open %s log file', $RCName) . ':') . ' ' . $RcFile),
  3646. $q->p(T('Error was') . ':'), $q->pre($!), $q->p(T('Note: This error is normal if no changes have been made.'));
  3647. }
  3648. # Move the old stuff from rc to temp
  3649. my @rc = split(/\n/, $data);
  3650. my @tmp = ();
  3651. for my $line (@rc) {
  3652. my ($ts, $id, $minor, $summary, $host, @rest) = split(/$FS/, $line);
  3653. last if $ts >= $starttime;
  3654. push(@tmp, join($FS, $ts, $id, $minor, $summary, 'Anonymous', @rest));
  3655. }
  3656. print $q->p(Ts('Moving %s log entries.', scalar(@tmp)));
  3657. if (@tmp) {
  3658. # Write new files, and backups
  3659. AppendStringToFile($RcOldFile, join("\n", @tmp) . "\n");
  3660. WriteStringToFile($RcFile . '.old', $data);
  3661. splice(@rc, 0, scalar(@tmp)); # strip
  3662. WriteStringToFile($RcFile, @rc ? join("\n", @rc) . "\n" : '');
  3663. }
  3664. if (opendir(DIR, $RssDir)) { # cleanup if they should expire anyway
  3665. foreach (readdir(DIR)) {
  3666. unlink "$RssDir/$_" if $Now - (stat($_))[9] > $RssCacheHours * 3600;
  3667. }
  3668. closedir DIR;
  3669. }
  3670. foreach my $func (@MyMaintenance) {
  3671. $func->();
  3672. }
  3673. WriteStringToFile($fname, 'Maintenance done at ' . TimeToText($Now));
  3674. ReleaseLock();
  3675. print $q->p(T('Main lock released.')), $q->end_div();
  3676. PrintFooter();
  3677. }
  3678. sub PageDeletable {
  3679. return unless $KeepDays;
  3680. my $expirets = $Now - ($KeepDays * 86400); # 24*60*60
  3681. return 0 if $Page{ts} >= $expirets;
  3682. return PageMarkedForDeletion();
  3683. }
  3684. sub PageMarkedForDeletion {
  3685. # Only pages explicitly marked for deletion or whitespace-only pages
  3686. # are deleted; taking into account the very rare possiblity of a
  3687. # read error and the page text being undefined.
  3688. return 1 if defined $Page{text} and $Page{text} =~ /^\s*$/;
  3689. return $DeletedPage && substr($Page{text}, 0, length($DeletedPage)) eq $DeletedPage;
  3690. }
  3691. sub DeletePage { # Delete must be done inside locks.
  3692. my $id = shift;
  3693. ValidIdOrDie($id);
  3694. AppendStringToFile($DeleteFile, "$id\n");
  3695. foreach my $name (GetPageFile($id), GetKeepFiles($id), GetKeepDir($id), GetLockedPageFile($id), $IndexFile) {
  3696. unlink $name if -f $name;
  3697. rmdir $name if -d $name;
  3698. }
  3699. ReInit($id);
  3700. delete $IndexHash{$id};
  3701. @IndexList = sort(keys %IndexHash);
  3702. return ''; # no error
  3703. }
  3704. sub DoEditLock {
  3705. return unless UserIsAdminOrError();
  3706. print GetHeader('', T('Set or Remove global edit lock'));
  3707. my $fname = "$NoEditFile";
  3708. if (GetParam("set", 1)) {
  3709. WriteStringToFile($fname, 'editing locked.');
  3710. } else {
  3711. unlink($fname);
  3712. }
  3713. utime time, time, $IndexFile; # touch index file
  3714. print $q->p(-f $fname ? T('Edit lock created.') : T('Edit lock removed.'));
  3715. PrintFooter();
  3716. }
  3717. sub DoPageLock {
  3718. return unless UserIsAdminOrError();
  3719. print GetHeader('', T('Set or Remove page edit lock'));
  3720. my $id = GetParam('id', '');
  3721. ValidIdOrDie($id);
  3722. my $fname = GetLockedPageFile($id);
  3723. if (GetParam('set', 1)) {
  3724. WriteStringToFile($fname, 'editing locked.');
  3725. } else {
  3726. unlink($fname);
  3727. }
  3728. utime time, time, $IndexFile; # touch index file
  3729. print $q->p(-f $fname ? Ts('Lock for %s created.', GetPageLink($id))
  3730. : Ts('Lock for %s removed.', GetPageLink($id)));
  3731. PrintFooter();
  3732. }
  3733. sub DoShowVersion {
  3734. print GetHeader('', T('Displaying Wiki Version')), $q->start_div({-class=>'content version'});
  3735. print $WikiDescription, $q->p($q->server_software()),
  3736. $q->p(sprintf('Perl v%vd', $^V)),
  3737. $q->p($ENV{MOD_PERL} ? $ENV{MOD_PERL} : "no mod_perl"), $q->p('CGI: ', $CGI::VERSION),
  3738. $q->p('LWP::UserAgent ', eval { local $SIG{__DIE__}; require LWP::UserAgent; $LWP::UserAgent::VERSION; }),
  3739. $q->p('XML::RSS: ', eval { local $SIG{__DIE__}; require XML::RSS; $XML::RSS::VERSION; }),
  3740. $q->p('XML::Parser: ', eval { local $SIG{__DIE__}; $XML::Parser::VERSION; });
  3741. print $q->p('diff: ' . (`diff --version` || $!)), $q->p('diff3: ' . (`diff3 --version` || $!)) if $UseDiff;
  3742. print $q->end_div();
  3743. PrintFooter();
  3744. }
  3745. sub DoDebug {
  3746. print GetHeader('', T('Debugging Information')),
  3747. $q->start_div({-class=>'content debug'});
  3748. foreach my $func (@Debugging) { $func->() }
  3749. print $q->end_div();
  3750. PrintFooter();
  3751. }
  3752. sub DoSurgeProtection {
  3753. return unless $SurgeProtection;
  3754. my $name = GetParam('username', $q->remote_addr());
  3755. return unless $name;
  3756. ReadRecentVisitors();
  3757. AddRecentVisitor($name);
  3758. if (RequestLockDir('visitors')) { # not fatal
  3759. WriteRecentVisitors();
  3760. ReleaseLockDir('visitors');
  3761. if (DelayRequired($name)) {
  3762. ReportError(Ts('Too many connections by %s', $name)
  3763. . ': ' . Tss('Please do not fetch more than %1 pages in %2 seconds.',
  3764. $SurgeProtectionViews, $SurgeProtectionTime),
  3765. '503 SERVICE UNAVAILABLE');
  3766. }
  3767. } elsif (GetParam('action', '') ne 'unlock') {
  3768. ReportError(Ts('Could not get %s lock', 'visitors') . ': ' . Ts('Check whether the web server can create the directory %s and whether it can create files in it.', $TempDir), '503 SERVICE UNAVAILABLE');
  3769. }
  3770. }
  3771. sub DelayRequired {
  3772. my $name = shift;
  3773. my @entries = @{$RecentVisitors{$name}};
  3774. my $ts = $entries[$SurgeProtectionViews];
  3775. return ($Now - $ts) < $SurgeProtectionTime;
  3776. }
  3777. sub AddRecentVisitor {
  3778. my $name = shift;
  3779. my $value = $RecentVisitors{$name};
  3780. my @entries = ($Now);
  3781. push(@entries, @{$value}) if $value;
  3782. $RecentVisitors{$name} = \@entries;
  3783. }
  3784. sub ReadRecentVisitors {
  3785. my ($status, $data) = ReadFile($VisitorFile);
  3786. %RecentVisitors = ();
  3787. return unless $status;
  3788. foreach (split(/\n/, $data)) {
  3789. my @entries = split /$FS/;
  3790. my $name = shift(@entries);
  3791. $RecentVisitors{$name} = \@entries if $name;
  3792. }
  3793. }
  3794. sub WriteRecentVisitors {
  3795. my $data = '';
  3796. my $limit = $Now - $SurgeProtectionTime;
  3797. foreach my $name (keys %RecentVisitors) {
  3798. my @entries = @{$RecentVisitors{$name}};
  3799. if ($entries[0] >= $limit) { # if the most recent one is too old, do not keep
  3800. $data .= join($FS, $name, @entries[0 .. $SurgeProtectionViews - 1]) . "\n";
  3801. }
  3802. }
  3803. WriteStringToFile($VisitorFile, $data);
  3804. }
  3805. sub TextIsFile { $_[0] =~ /^#FILE (\S+) ?(\S+)?\n/ }
  3806. sub AddModuleDescription { # cannot use $q here because this is module init time
  3807. my ($filename, $page, $dir, $tag) = @_;
  3808. my $src = "http://git.savannah.gnu.org/cgit/oddmuse.git/tree/modules/$dir" . UrlEncode($filename) . ($tag ? '?' . $tag : '');
  3809. my $doc = 'http://www.oddmuse.org/cgi-bin/oddmuse/' . UrlEncode(FreeToNormal($page));
  3810. $ModulesDescription .= "<p><a href=\"$src\">" . QuoteHtml($filename) . "</a>" . ($tag ? " ($tag)" : '');
  3811. $ModulesDescription .= T(', see') . " <a href=\"$doc\">" . QuoteHtml($page) . "</a>" if $page;
  3812. $ModulesDescription .= "</p>";
  3813. }
  3814. DoWikiRequest() if $RunCGI and not exists $ENV{MOD_PERL}; # Do everything.
  3815. 1; # In case we are loaded from elsewhere