wiki.pl 157 KB

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