wiki.pl 161 KB

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