script/wiki.pl untested

filter: Statementstmt 0.0% 0 / 881 Branchbran 0.0% 0 / 368 Conditioncond 0.0% 0 / 123 MC/DCmcdc 0.0% 0 / 78 Subroutinesub 0.0% 0 / 65 Podpod 0.0% 0 / 50 totaltotal 0.0% 0 / 1565 CC 182 SCAR 49.3
CC
182
Cov
0%
DoOtherRequest
420.0
DoPost
380.0
BrowsePage
272.0
CRAP 138.5
1 #!/usr/local/bin/perl
2 # vi:et:tw=0:sm:ai:ts=2:sw=2
3 #
4 # wiki.pl - PurpleWiki
5 #
6 # $Id: wiki.pl 474 2004-08-11 08:28:49Z cdent $
7 #
8 # Copyright (c) Blue Oxen Associates 2002. All rights reserved.
9 #
10 # This file is part of PurpleWiki. PurpleWiki is derived from:
11 #
12 # UseModWiki v0.92 (c) Clifford A. Adams 2000-2001
13 # AtisWiki v0.3 (c) Markus Denker 1998
14 # CVWiki CVS-patches (c) Peter Merel 1997
15 # The Original WikiWikiWeb (c) Ward Cunningham
16 #
17 # PurpleWiki is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 # GNU General Public License for more details.
26 #
27 # You should have received a copy of the GNU General Public License
28 # along with this program; if not, write to the
29 # Free Software Foundation, Inc.
30 # 59 Temple Place, Suite 330
31 # Boston, MA 02111-1307 USA
32  
33 package UseModWiki;
34 use strict;
35 use CGI;
36 use CGI::Carp qw(fatalsToBrowser);
37 use CGI::Session;
38 use Digest::MD5;
39 use PurpleWiki::ACL;
40 use PurpleWiki::Config;
41 use PurpleWiki::Database;
42 use PurpleWiki::Database::Page;
43 use PurpleWiki::Database::KeptRevision;
44 use PurpleWiki::Database::User::UseMod;
45 use PurpleWiki::Parser::WikiText;
46 use PurpleWiki::Search::Engine;
47  
48 my $CONFIG_DIR='/var/www/wikidb';
49  
50 our $VERSION;
51 $VERSION = sprintf("%d", q$Id: wiki.pl 474 2004-08-11 08:28:49Z cdent $ =~ /\s(\d+)\s/);
52  
53 local $| = 1; # Do not buffer output (localized for mod_perl)
54  
55 my $InterSiteInit = 0;
56 my %InterSite;
57 my $user; # our reference to the logged in user
58 my $session; # CGI::Session object
59 my $visitedPagesCache;
60 my $visitedPagesCacheSize = 7;
61  
62 my $q; # CGI query reference
63 my $Now; # The time at the beginning of the request
64  
65 my $TimeZoneOffset; # User's prefernce for timezone. FIXME: can we
66 # get this off $user reliably? Doesn't look
67 # worth it.
68  
69 # we only need one of each these per run
70 my $config = new PurpleWiki::Config($CONFIG_DIR);
71 my $wikiParser = PurpleWiki::Parser::WikiText->new;
72 # FIXME: would be cool if there were a way to factory these based off a
73 # config value.
74 my $userDb = PurpleWiki::Database::User::UseMod->new;
75 my $acl = PurpleWiki::ACL->new;
76  
77 # Select and load a template driver
78 my $templateDriver = $config->TemplateDriver();
79 my $templateClass = "PurpleWiki::Template::$templateDriver";
80 eval "require $templateClass";
81 my $wikiTemplate = $templateClass->new;
82  
83 # check for i-names support
84 if ($config->UseINames) {
85 require XDI::SPIT;
86 }
87  
88 # Set our umask if one was put in the config file. - matthew
89 umask(oct($config->Umask)) if defined $config->Umask;
90  
91 # The "main" program, called from the end of this script file.
92 sub DoWikiRequest {
93 InitRequest() or return;
94  
95 # Instantiate PurpleWiki parser.
96  
97 if (not DoBrowseRequest()) {
98 DoOtherRequest();
99 }
100 &logSession;
101 }
102  
103 # == Common and cache-browsing code ====================================
104  
105 sub InitRequest {
106 $CGI::POST_MAX = $config->MaxPost;
107 $CGI::DISABLE_UPLOADS = 1; # no uploads
108 $q = new CGI;
109  
110 $Now = time; # Reset in case script is persistent
111 $PurpleWiki::Page::MainPage = "."; # For subpages only, the name of the top-level page
112 PurpleWiki::Database::CreateDir($config->DataDir); # Create directory if it doesn't exist
113 if (!-d $config->DataDir) {
114 $wikiTemplate->vars(&globalTemplateVars,
115 dataDir => $config->DataDir);
116 print GetHttpHeader() . $wikiTemplate->process('errors/dataDirCannotCreate');
117 return 0;
118 }
119 InitCookie(); # Reads in user data
120 return 1;
121 }
122  
123 sub InitCookie {
124 $TimeZoneOffset = 0;
125 undef $q->{'.cookies'}; # Clear cache if it exists (for SpeedyCGI)
126  
127 my $sid = $q->cookie($config->SiteName);
128 $session = CGI::Session->new("driver:File", $sid,
129 {Directory => "$CONFIG_DIR/sessions"});
130 my $userId = $session->param('userId');
131 $user = $userDb->loadUser($userId) if ($userId);
132 $session->clear(['userId']) if (!$user);
133  
134 if ($user && $user->tzOffset != 0) {
135 $TimeZoneOffset = $user->tzOffset * (60 * 60);
136 }
137  
138 $visitedPagesCache = $session->param('visitedPagesCache') || {};
139 }
140  
141 sub DoBrowseRequest {
142 my ($id, $action, $text);
143 my $page;
144  
145 if (!$q->param) { # No parameter
146 BrowsePage($config->HomePage);
147 return 1;
148 }
149 $id = GetParam('keywords', '');
150 $page = new PurpleWiki::Database::Page('id' => $id);
151 if ($id) { # Just script?PageName
152 if ($config->FreeLinks && (!$page->pageExists())) {
153 $id = FreeToNormal($id);
154 }
155 BrowsePage($id) if ValidIdOrDie($id);
156 return 1;
157 }
158 $action = lc(GetParam('action', ''));
159 $id = GetParam('id', '');
160 $page = new PurpleWiki::Database::Page('id' => $id);
161 if ($action eq 'browse') {
162 if ($config->FreeLinks && (!$page->pageExists())) {
163 $id = FreeToNormal($id);
164 }
165 BrowsePage($id) if ValidIdOrDie($id);
166 return 1;
167 } elsif ($action eq 'rc') {
168 BrowsePage($config->RCName);
169 return 1;
170 } elsif ($action eq 'random') {
171 DoRandom();
172 return 1;
173 } elsif ($action eq 'history') {
174 DoHistory($id) if ValidIdOrDie($id);
175 return 1;
176 }
177 return 0; # Request not handled
178 }
179  
180 sub BrowsePage {
181 my $id = shift;
182 my $body;
183 my ($fullHtml, $oldId, $allDiff, $showDiff, $openKept);
184 my ($revision, $goodRevision, $diffRevision, $newText);
185  
186 my ($page, $section, $text, $keptRevision, $keptSection);
187  
188 my ($userId, $username);
189 if ($user) {
190 $userId = $user->id;
191 $username= $user->username;
192 }
193 $page = new PurpleWiki::Database::Page('id' => $id, 'now' => $Now,
194 'userID' => $userId,
195 'username' => $username);
196 $page->openPage();
197 $section = $page->getSection();
198 $text = $page->getText();
199 $newText = $text->getText();
200 $keptRevision = new PurpleWiki::Database::KeptRevision(id => $id);
201  
202 $revision = GetParam('revision', '');
203 $revision =~ s/\D//g; # Remove non-numeric chars
204 $goodRevision = $revision; # Non-blank only if exists
205 if ($revision ne '') {
206 if (!$keptRevision->hasRevision($revision)) {
207 $goodRevision = '';
208 }
209 }
210
211 # Handle a single-level redirect
212 $oldId = GetParam('oldid', '');
213 if (($oldId eq '') && (substr($text->getText(), 0, 10) eq '#REDIRECT ')) {
214 $oldId = $id;
215 if (($config->FreeLinks) && ($text->getText() =~ /\#REDIRECT\s+\[\[.+\]\]/)) {
216 ($id) = ($text->getText() =~ /\#REDIRECT\s+\[\[(.+)\]\]/);
217 $id = FreeToNormal($id);
218 } else {
219 ($id) = ($text->getText() =~ /\#REDIRECT\s+(\S+)/);
220 }
221 if (ValidId($id) eq '') {
222 # Later consider revision in rebrowse?
223 ReBrowsePage($id, $oldId, 0);
224 return;
225 } else { # Not a valid target, so continue as normal page
226 $id = $oldId;
227 $oldId = '';
228 }
229 }
230 $PurpleWiki::Page::MainPage = $id;
231 $PurpleWiki::Page::MainPage =~ s|/.*||; # Only the main page name (remove subpage)
232  
233 if ($revision ne '') {
234 # Later maybe add edit time?
235 if ($goodRevision ne '') {
236 $text = $keptRevision->getRevision($revision)->getText();
237 }
238 }
239 $allDiff = GetParam('alldiff', 0);
240  
241 if ($allDiff != 0) {
242 $allDiff = GetParam('defaultdiff', 1);
243 }
244  
245 if (($id eq $config->RCName) && GetParam('norcdiff', 1)) {
246 $allDiff = 0; # Only show if specifically requested
247 }
248  
249 $showDiff = GetParam('diff', $allDiff);
250  
251 my $pageName = $id;
252 if ($config->FreeLinks) {
253 $pageName =~ s/_/ /g;
254 }
255  
256 my $lastEdited = TimeToText($section->getTS());
257  
258 if ($config->UseDiff && $showDiff) {
259 $diffRevision = $goodRevision;
260 $diffRevision = GetParam('diffrevision', $diffRevision);
261  
262 DoDiff($page, $keptRevision, $showDiff, $id, $pageName, $lastEdited,
263 $diffRevision, $newText);
264 return;
265 }
266  
267 $body = WikiToHTML($id, $text->getText());
268  
269 &updateVisitedPagesCache($id);
270 if ($id eq $config->RCName) {
271 DoRc($id, $pageName, $revision, $goodRevision, $lastEdited, $body);
272 return;
273 }
274 my @vPages = &visitedPages;
275 my $keywords = $id;
276 $keywords =~ s/_/\+/g if ($config->FreeLinks);
277  
278 my $editRevisionString = '';
279 if ($goodRevision) {
280 $editRevisionString = "&revision=$revision";
281 }
282  
283 $wikiTemplate->vars(&globalTemplateVars,
284 pageName => $pageName,
285 expandedPageName => &expandPageName($pageName),
286 visitedPages => \@vPages,
287 showRevision => $revision,
288 revision => $goodRevision,
289 body => $body,
290 lastEdited => $lastEdited,
291 pageUrl => $config->ScriptName . "?$id",
292 backlinksUrl => $config->ScriptName . "?search=$keywords",
293 editUrl =>
294 $config->ScriptName . "?action=edit&id=$id" .
295 $editRevisionString,
296 revisionsUrl =>
297 $config->ScriptName . "?action=history&id=$id",
298 diffUrl =>
299 $config->ScriptName .
300 "?action=browse&diff=1&id=$id");
301 print GetHttpHeader() . $wikiTemplate->process('viewPage');
302 }
303  
304 sub ReBrowsePage {
305 my ($id, $oldId, $isEdit) = @_;
306  
307 if ($oldId ne "") { # Target of #REDIRECT (loop breaking)
308 print GetRedirectpage("action=browse&id=$id&oldid=$oldId",
309 $id, $isEdit);
310 } else {
311 print GetRedirectPage($id, $id, $isEdit);
312 }
313 }
314  
315 sub DoRc {
316 my ($id, $pageName, $revision, $goodRevision, $lastEdited, $body) = @_;
317 my $starttime = 0;
318 my $daysago;
319 my @rcDays;
320  
321 foreach my $days (@{$config->RcDays}) {
322 push @rcDays, { num => $days,
323 url => $config->ScriptName .
324 "?action=rc&days=$days" };
325 }
326 if (GetParam("from", 0)) {
327 $starttime = GetParam("from", 0);
328 }
329 else {
330 $daysago = GetParam("days", 0);
331 $daysago = GetParam("rcdays", 0) if ($daysago == 0);
332 if ($daysago) {
333 $starttime = $Now - ((24*60*60)*$daysago);
334 }
335 }
336 if ($starttime == 0) {
337 $starttime = $Now - ((24*60*60) * $config->RcDefault);
338 $daysago = $config->RcDefault;
339 }
340 my $rcRef = PurpleWiki::Database::recentChanges($config, $starttime);
341 my @recentChanges;
342 my $prevDate;
343 foreach my $page (@{$rcRef}) {
344 my $date = CalcDay($page->{timeStamp});
345 if ($date ne $prevDate) {
346 push @recentChanges, { date => $date, pages => [] };
347 $prevDate = $date;
348 }
349 push @{$recentChanges[$#recentChanges]->{pages}},
350 { id => $page->{id},
351 pageName => $page->{pageName},
352 time => CalcTime($page->{timeStamp}),
353 numChanges => $page->{numChanges},
354 summary => QuoteHtml($page->{summary}),
355 userName => $page->{userName},
356 userId => $page->{userId},
357 host => $page->{host},
358 diffUrl => $config->ScriptName .
359 '?action=browse&diff=1&id=' . $page->{id},
360 changeUrl => $config->ScriptName .
361 '?action=history&id=' . $page->{id} };
362 }
363 my @vPages = &visitedPages;
364 $wikiTemplate->vars(&globalTemplateVars,
365 pageName => $pageName,
366 expandedPageName => &expandPageName($pageName),
367 visitedPages => \@vPages,
368 showRevision => $revision,
369 revision => $goodRevision,
370 body => $body,
371 daysAgo => $daysago,
372 rcDays => \@rcDays,
373 changesFrom => TimeToText($starttime),
374 currentDate => TimeToText($Now),
375 recentChanges => \@recentChanges,
376 lastEdited => $lastEdited,
377 pageUrl => $config->ScriptName . "?$id",
378 backlinksUrl => $config->ScriptName . "?search=$id",
379 editUrl => $config->ScriptName . "?action=edit&id=$id",
380 revisionsUrl => $config->ScriptName . "?action=history&id=$id",
381 diffUrl => $config->ScriptName . "?action=browse&diff=1&id=$id");
382 print GetHttpHeader() . $wikiTemplate->process('viewRecentChanges');
383 }
384  
385 sub DoRandom {
386 my ($id, @pageList);
387  
388 @pageList = PurpleWiki::Database::AllPagesList($config); # Optimize?
389 $id = $pageList[int(rand($#pageList + 1))];
390 ReBrowsePage($id, "", 0);
391 }
392  
393 sub DoHistory {
394 my ($id) = @_;
395 my $page;
396 my $text;
397 my $keptRevision;
398 my @pageHistory;
399  
400 $page = new PurpleWiki::Database::Page('id' => $id, 'now' => $Now);
401 $page->openPage();
402  
403 push @pageHistory, getRevisionHistory($id, $page->getSection, 1);
404 $keptRevision = new PurpleWiki::Database::KeptRevision(id => $id);
405 foreach my $section (reverse sort {$a->getRevision() <=> $b->getRevision()}
406 $keptRevision->getSections()) {
407 # If KeptRevision == Current Revision don't print it. - matthew
408 if ($section->getRevision() != $page->getSection()->getRevision()) {
409 push @pageHistory, getRevisionHistory($id, $section, 0);
410 }
411 }
412  
413 my @vPages = &visitedPages;
414 $wikiTemplate->vars(&globalTemplateVars,
415 pageName => $id,
416 visitedPages => \@vPages,
417 pageHistory => \@pageHistory);
418 print GetHttpHeader() . $wikiTemplate->process('viewPageHistory');
419 }
420  
421 sub getRevisionHistory {
422 my ($id, $section, $isCurrent) = @_;
423 my ($rev, $summary, $host, $user, $uid, $ts, $pageUrl, $diffUrl, $editUrl);
424  
425 my $text = $section->getText();
426 $rev = $section->getRevision();
427 $summary = $text->getSummary();
428 if ((defined($section->getHost())) && ($section->getHost() ne '')) {
429 $host = $section->getHost();
430 } else {
431 $host = $section->getIP();
432 $host =~ s/\d+$/xxx/; # Be somewhat anonymous (if no host)
433 }
434 $user = $section->getUsername();
435 $uid = $section->getID();
436 $ts = $section->getTS();
437  
438 if ($isCurrent) {
439 $pageUrl = $config->ScriptName . "?$id";
440 }
441 else {
442 $pageUrl = $config->ScriptName .
443 "?action=browse&amp;id=$id&amp;revision=$rev";
444 $diffUrl = $config->ScriptName .
445 "?action=browse&amp;diff=1&amp;id=$id&amp;diffrevision=$rev";
446 $editUrl = $config->ScriptName .
447 "?action=edit&amp;id=$id&amp;revision=$rev";
448 }
449 if (defined($summary) && ($summary ne "") && ($summary ne "*")) {
450 $summary = QuoteHtml($summary); # Thanks Sunir! :-)
451 }
452 else {
453 $summary = '';
454 }
455 return { revision => $rev,
456 dateTime => TimeToText($ts),
457 host => $host,
458 user => $user,
459 summary => $summary,
460 pageUrl => $pageUrl,
461 diffUrl => $diffUrl,
462 editUrl => $editUrl };
463 }
464  
465 # ==== page-oriented functions ====
466 sub GetHttpHeader {
467 my $cookie = $q->cookie(-name => $config->SiteName,
468 -value => $session->id,
469 -path => $config->ScriptDir,
470 -expires => '+7d');
471 if ($config->HttpCharset ne '') {
472 return $q->header(-cookie=>$cookie,
473 -type=>"text/html; charset=" . $config->HttpCharset);
474 }
475 return $q->header(-cookie=>$cookie);
476 }
477  
478 # Returns the URL of a page after it has
479 # been edited. This used to do lots of
480 # hoops if CGI.pm was not being used,
481 # but we don't worry about that anymore.
482 sub GetRedirectPage {
483 my ($newid, $name, $isEdit) = @_;
484 my ($url, $html);
485  
486 if ($config->FullUrl ne "") {
487 $url = $config->FullUrl;
488 } else {
489 $url = $q->url(-full=>1);
490 }
491  
492 $url = $url . "?" . $newid;
493  
494 $html = $q->redirect(-uri=>$url);
495 return $html;
496 }
497  
498 # ==== Common wiki markup ====
499 sub WikiToHTML {
500 # Use the PurpleWiki::View::wikihtml driver to parse wiki pages to HTML
501 my $id = shift;
502 my $pageText = shift;
503  
504 my $wiki = $wikiParser->parse($pageText, 'freelink' => $config->FreeLinks);
505 my $url = $q->url(-full => 1) . '?' . $id;
506 return $wiki->view('wikihtml', url => $url, pageName => $id);
507 }
508  
509 sub QuoteHtml {
510 my ($html) = @_;
511  
512 $html =~ s/&/&amp;/g;
513 $html =~ s/</&lt;/g;
514 $html =~ s/>/&gt;/g;
515 if (1) { # Make an official option?
516 $html =~ s/&amp;([#a-zA-Z0-9]+);/&$1;/g; # Allow character references
517 }
518 return $html;
519 }
520  
521 # ==== Misc. functions ====
522 sub ValidId {
523 my ($id) = @_;
524  
525 if (length($id) > 120) {
526 return "pageNameTooLong";
527 }
528 if ($id =~ m| |) {
529 return "pageNameTooManyChars";
530 }
531 if ($config->UseSubpage()) {
532 if ($id =~ m|.*/.*/|) {
533 return "pageNameTooManySlashes";
534 }
535 if ($id =~ /^\//) {
536 return "pageNameNoMainPage";
537 }
538 if ($id =~ /\/$/) {
539 return "pageNameMissingSubpage";
540 }
541 }
542  
543 my $linkpattern = $config->LinkPattern;
544 my $freelinkpattern = $config->FreeLinkPattern;
545  
546 if ($config->FreeLinks()) {
547 $id =~ s/ /_/g;
548 if (!$config->UseSubpage()) {
549 if ($id =~ /\//) {
550 return "pageNameSlashNotAllowed";
551 }
552 }
553 if (!($id =~ m|^$freelinkpattern$|)) {
554 return "pageNameInvalid";
555 }
556 if ($id =~ m|\.db$|) {
557 return "pageNameInvalid";
558 }
559 if ($id =~ m|\.lck$|) {
560 return "pageNameInvalid";
561 }
562 return "";
563 } else {
564 if (!($id =~ /^$linkpattern$/)) {
565 return "pageNameInvalid";
566 }
567 }
568 return "";
569 }
570  
571 sub ValidIdOrDie {
572 my $id = shift;
573 my $error;
574  
575 $wikiTemplate->vars(&globalTemplateVars,
576 pageName => $id);
577 $error = ValidId($id);
578 if ($error ne "") {
579 print GetHttpHeader() . $wikiTemplate->process('errors/$error');
580 return 0;
581 }
582 return 1;
583 }
584  
585 sub CalcDay {
586 my ($ts) = @_;
587  
588 $ts += $TimeZoneOffset;
589 my ($sec, $min, $hour, $mday, $mon, $year) = localtime($ts);
590  
591 return ("January", "February", "March", "April", "May", "June",
592 "July", "August", "September", "October", "November",
593 "December")[$mon]. " " . $mday . ", " . ($year+1900);
594 }
595  
596 sub CalcTime {
597 my ($ts) = @_;
598 my ($ampm, $mytz);
599  
600 $ts += $TimeZoneOffset;
601 my ($sec, $min, $hour, $mday, $mon, $year) = localtime($ts);
602  
603 $mytz = "";
604 if (($TimeZoneOffset == 0) && ($config->ScriptTZ ne "")) {
605 $mytz = " " . $config->ScriptTZ;
606 }
607 $ampm = "";
608 if ($config->UseAmPm) {
609 $ampm = " am";
610 if ($hour > 11) {
611 $ampm = " pm";
612 $hour = $hour - 12;
613 }
614 $hour = 12 if ($hour == 0);
615 }
616 $min = "0" . $min if ($min<10);
617 return $hour . ":" . $min . $ampm . $mytz;
618 }
619  
620 sub TimeToText {
621 my ($t) = @_;
622  
623 return CalcDay($t) . " " . CalcTime($t);
624 }
625  
626 sub GetParam {
627 my ($name, $default) = @_;
628 my $result;
629  
630 $result = $q->param($name);
631 if (!defined($result)) {
632 if ($user && length($user->getField($name))) {
633 $result = $user->getField($name);
634 } else {
635 $result = $default;
636 }
637 }
638 return $result;
639 }
640  
641 sub GetRemoteHost {
642 my ($doMask) = @_;
643 my ($rhost, $iaddr);
644  
645 $rhost = $ENV{REMOTE_HOST};
646 if ($rhost eq "") {
647 # Catch errors (including bad input) without aborting the script
648 eval 'use Socket; $iaddr = inet_aton($ENV{REMOTE_ADDR});'
649 . '$rhost = gethostbyaddr($iaddr, AF_INET)';
650 }
651 if ($rhost eq "") {
652 $rhost = $ENV{REMOTE_ADDR};
653 $rhost =~ s/\d+$/xxx/ if ($doMask); # Be somewhat anonymous
654 }
655 return $rhost;
656 }
657  
658 sub FreeToNormal {
659 my ($id) = @_;
660  
661 $id =~ s/ /_/g;
662 $id = ucfirst($id);
663 if (index($id, '_') > -1) { # Quick check for any space/underscores
664 $id =~ s/__+/_/g;
665 $id =~ s/^_//;
666 $id =~ s/_$//;
667 if ($config->UseSubpage) {
668 $id =~ s|_/|/|g;
669 $id =~ s|/_|/|g;
670 }
671 }
672 if ($config->FreeUpper) {
673 # Note that letters after ' are *not* capitalized
674 if ($id =~ m|[-_.,\(\)/][a-z]|) { # Quick check for non-canonical case
675 $id =~ s|([-_.,\(\)/])([a-z])|$1 . uc($2)|ge;
676 }
677 }
678 return $id;
679 }
680 #END_OF_BROWSE_CODE
681  
682 # == Page-editing and other special-action code ========================
683  
684 sub DoOtherRequest {
685 my ($id, $action, $text, $search);
686  
687 $action = GetParam("action", "");
688 $id = GetParam("id", "");
689 my $iname = &GetParam("xri_iname", "");
690 if ($action ne "") {
691 $action = lc($action);
692 if ($action eq "edit") {
693 DoEdit($id, 0, 0, "", 0) if ValidIdOrDie($id);
694 } elsif ($action eq "unlock") {
695 DoUnlock();
696 } elsif ($action eq "index") {
697 DoIndex();
698 } elsif ($action eq "editprefs") {
699 DoEditPrefs();
700 } elsif ($config->UseINames && $action eq "getiname") {
701 if (!$user) {
702 &DoGetIname();
703 }
704 else { # return an error
705 }
706 } elsif ($action eq "login") {
707 DoEnterLogin();
708 } elsif ($action eq "newlogin") {
709 $user = undef;
710 DoEditPrefs(); # Also creates new ID
711 } elsif ($action eq "logout") {
712 &DoLogout;
713 } elsif ($action eq 'rss') {
714 require PurpleWiki::Syndication::Rss;
715 my $rss = new PurpleWiki::Syndication::Rss;
716 print $q->header(-type => 'text/xml') .
717 $rss->getRSS;
718 } else {
719 # Later improve error reporting
720 $wikiTemplate->vars(&globalTemplateVars,
721 action => $action);
722 print GetHttpHeader() . $wikiTemplate->process('errors/actionInvalid');
723 }
724 return;
725 }
726 elsif ($config->UseINames && $iname) {
727 my $xsid = &GetParam('xri_xsid', '');
728 &DoIname($iname, $xsid);
729 return;
730 }
731  
732 $iname = &GetParam("iname", "");
733 if ($config->UseINames && $iname) {
734 my $localId = &GetParam("local_id", "");
735 my $rrsid = &GetParam("rrsid", "");
736 &DoAssociateIname($iname, $localId, $rrsid);
737 return;
738 }
739
740 if (&GetParam("edit_prefs", 0)) {
741 &DoUpdatePrefs();
742 return;
743 }
744 if (GetParam("enter_login", 0)) {
745 DoLogin();
746 return;
747 }
748 $search = GetParam("search", "");
749 if (($search ne "") || (GetParam("dosearch", "") ne "")) {
750 DoSearch($search);
751 return;
752 }
753 # Handle posted pages
754 if (GetParam("oldtime", "") ne "") {
755 $id = GetParam("title", "");
756 DoPost() if ValidIdOrDie($id);
757 return;
758 }
759 # Later improve error message
760 $wikiTemplate->vars(&globalTemplateVars);
761 print GetHttpHeader() . $wikiTemplate->process('errors/urlInvalid');
762 }
763  
764 sub DoEdit {
765 my ($id, $isConflict, $oldTime, $newText, $preview) = @_;
766 my ($header, $editRows, $editCols, $revision, $oldText);
767 my ($summary, $isEdit, $pageTime);
768  
769 my $page;
770 my $section;
771 my $text;
772 my $keptRevision;
773  
774 my $pageName = $id;
775 if ($config->FreeLinks) {
776 $pageName =~ s/_/ /g;
777 }
778  
779 if (!$acl->canEdit($user, $id)) {
780 $wikiTemplate->vars(&globalTemplateVars);
781 print GetHttpHeader() . $wikiTemplate->process('errors/editBlocked');
782 return;
783 }
784 elsif (!$config->EditAllowed || -f $config->DataDir . "/noedit") {
785 $wikiTemplate->vars(&globalTemplateVars);
786 print GetHttpHeader() . $wikiTemplate->process('errors/editSiteReadOnly');
787 return;
788 }
789  
790 $page = new PurpleWiki::Database::Page('id' => $id);
791  
792 if (-f $page->getLockedPageFile()) {
793 $wikiTemplate->vars(&globalTemplateVars);
794 print GetHttpHeader() . $wikiTemplate->process('errors/editNotAllowed');
795 return;
796 }
797  
798 $keptRevision = new PurpleWiki::Database::KeptRevision(id => $id);
799 my ($username, $userId);
800 if ($user) {
801 $userId = $user->id;
802 $username = $user->username;
803 }
804 $page = new PurpleWiki::Database::Page('id' => $id, 'now' => $Now,
805 'username' => $username,
806 'userID' => $userId);
807 $page->openPage();
808 # FIXME: ordering is import in these next two, it shouldn't be
809 $text = $page->getText();
810 $section = $page->getSection();
811 $pageTime = $section->getTS();
812
813 # Old revision handling
814 $revision = GetParam('revision', '');
815 $revision =~ s/\D//g; # Remove non-numeric chars
816 if ($revision ne '') {
817 if (!$keptRevision->hasRevision($revision)) {
818 $revision = '';
819 # Later look for better solution, like error message?
820 } else {
821 # replace text with the revision we care about
822 $text = $keptRevision->getRevision($revision)->getText();
823 }
824 }
825  
826 $oldText = $text->getText();
827  
828 my @vPages = &visitedPages;
829  
830 if ($preview && !$isConflict) {
831 $oldText = $newText;
832 }
833  
834 if ($isConflict) {
835 $wikiTemplate->vars(&globalTemplateVars,
836 visitedPages => \@vPages,
837 id => $id,
838 pageName => $pageName,
839 revision => $revision,
840 isConflict => $isConflict,
841 lastSavedTime => TimeToText($oldTime),
842 currentTime => TimeToText($Now),
843 pageTime => $pageTime,
844 oldText => &QuoteHtml($oldText),
845 newText => &QuoteHtml($newText),
846 revisionsUrl => $config->ScriptName . "?action=history&amp;id=$id");
847 print GetHttpHeader() . $wikiTemplate->process('editConflict');
848 }
849 elsif ($preview) {
850 $wikiTemplate->vars(&globalTemplateVars,
851 visitedPages => \@vPages,
852 id => $id,
853 pageName => $pageName,
854 revision => $revision,
855 isConflict => $isConflict,
856 pageTime => $pageTime,
857 oldText => &QuoteHtml($oldText),
858 body => WikiToHTML($id, $oldText),
859 revisionsUrl => $config->ScriptName . "?action=history&amp;id=$id");
860 print GetHttpHeader() . $wikiTemplate->process('previewPage');
861 }
862 else {
863 $wikiTemplate->vars(&globalTemplateVars,
864 visitedPages => \@vPages,
865 id => $id,
866 pageName => $pageName,
867 revision => $revision,
868 pageTime => $pageTime,
869 oldText => &QuoteHtml($oldText),
870 revisionsUrl => $config->ScriptName . "?action=history&amp;id=$id");
871 print GetHttpHeader() . $wikiTemplate->process('editPage');
872 }
873  
874 $summary = GetParam("summary", "*");
875 }
876  
877 sub DoEditPrefs {
878 my ($check, $recentName, %labels);
879  
880 $recentName = $config->RCName;
881 $recentName =~ s/_/ /g;
882 &DoNewLogin() if (!$user);
883 $wikiTemplate->vars(&globalTemplateVars,
884 rcDefault => $config->RcDefault,
885 serverTime => &TimeToText($Now - $TimeZoneOffset),
886 tzOffset => &GetParam('tzoffset', 0));
887 print GetHttpHeader() . $wikiTemplate->process('preferencesEdit');
888 }
889  
890 sub GetFormText {
891 my ($name, $default, $size, $max) = @_;
892 my $text = GetParam($name, $default);
893  
894 return $q->textfield(-name=>"p_$name", -default=>$text,
895 -override=>1, -size=>$size, -maxlength=>$max);
896 }
897  
898 sub GetFormCheck {
899 my ($name, $default, $label) = @_;
900 my $checked = (GetParam($name, $default) > 0);
901  
902 return $q->checkbox(-name=>"p_$name", -override=>1, -checked=>$checked,
903 -label=>$label);
904 }
905  
906 sub DoUpdatePrefs {
907 my $username = &GetParam("p_username", "");
908 my $errorUserName = 0;
909 if ($username) {
910 if (length($username) > 50) { # Too long
911 $errorUserName = 1;
912 }
913 elsif ($userDb->idFromUsername($username)) { # already used
914 $errorUserName = 1;
915 }
916 else {
917 $user->username($username);
918 }
919 }
920 else {
921 $username = $user->username;
922 }
923  
924 my $password = &GetParam("p_password", "");
925  
926 my $passwordRemoved = 0;
927 my $passwordChanged = 0;
928 if ($password eq "") {
929 $passwordRemoved = 1;
930 $user->setField('password', undef);
931 }
932 elsif ($password ne "*") {
933 $passwordChanged = 1;
934 $user->setField('password', $password);
935 }
936  
937 UpdatePrefNumber("rcdays", 0, 0, 999999);
938 UpdatePrefCheckbox("rcnewtop");
939 UpdatePrefCheckbox("rcall");
940 UpdatePrefCheckbox("rcchangehist");
941 UpdatePrefCheckbox("editwide");
942  
943 if ($config->UseDiff) {
944 UpdatePrefCheckbox("norcdiff");
945 UpdatePrefCheckbox("diffrclink");
946 UpdatePrefCheckbox("alldiff");
947 UpdatePrefNumber("defaultdiff", 1, 1, 3);
948 }
949  
950 UpdatePrefNumber("rcshowedit", 1, 0, 2);
951 UpdatePrefNumber("tzoffset", 0, -999, 999);
952 UpdatePrefNumber("editrows", 1, 1, 999);
953 UpdatePrefNumber("editcols", 1, 1, 999);
954  
955 $TimeZoneOffset = GetParam("tzoffset", 0) * (60 * 60);
956  
957 if ($errorUserName) {
958 $wikiTemplate->vars(&globalTemplateVars,
959 userName => undef);
960 print &GetHttpHeader . $wikiTemplate->process('errors/usernameInvalid');
961 }
962 else {
963 $userDb->saveUser($user);
964 $wikiTemplate->vars(&globalTemplateVars,
965 passwordRemoved => $passwordRemoved,
966 passwordChanged => $passwordChanged,
967 serverTime => &TimeToText($Now-$TimeZoneOffset),
968 localTime => &TimeToText($Now));
969 print &GetHttpHeader . $wikiTemplate->process('preferencesUpdated');
970 }
971 }
972  
973 sub UpdatePrefCheckbox {
974 my ($param) = @_;
975 my $temp = GetParam("p_$param", "*");
976  
977 $user->setField($param, 1) if ($temp eq "on");
978 $user->setField($param, 0) if ($temp eq "*");
979 # It is possible to skip updating by using another value, like "2"
980 }
981  
982 sub UpdatePrefNumber {
983 my ($param, $integer, $min, $max) = @_;
984 my $temp = GetParam("p_$param", "*");
985  
986 return if ($temp eq "*");
987 $temp =~ s/[^-\d\.]//g;
988 $temp =~ s/\..*// if ($integer);
989 return if ($temp eq "");
990 return if (($temp < $min) || ($temp > $max));
991 $user->setField($param, $temp);
992 # Later consider returning status?
993 }
994  
995 sub DoIndex {
996 my @pages = PurpleWiki::Database::AllPagesList($config);
997 my @vPages = &visitedPages;
998  
999 $wikiTemplate->vars(&globalTemplateVars,
1000 visitedPages => \@vPages,
1001 pages => \@pages);
1002 print GetHttpHeader() . $wikiTemplate->process('pageIndex');
1003 }
1004  
1005 # Create a new user file/cookie pair
1006 sub DoNewLogin {
1007 # Later consider warning if cookie already exists
1008 # (maybe use "replace=1" parameter)
1009 $user = $userDb->createUser;
1010 $user->setField('rev', 1);
1011 $user->createTime($Now);
1012 $user->createIp($ENV{REMOTE_ADDR});
1013 $userDb->saveUser($user);
1014  
1015 $session->param('userId', $user->id);
1016 }
1017  
1018 sub CreateNewUser { # same as DoNewLogin, but no login
1019 # Later consider warning if cookie already exists
1020 # (maybe use "replace=1" parameter)
1021 $user = $userDb->createUser;
1022 $user->setField('rev', 1);
1023 $user->createTime($Now);
1024 $user->createIp($ENV{REMOTE_ADDR});
1025 $userDb->saveUser($user);
1026  
1027 # go back to being a guest
1028 my $localId = $user->id;
1029 $user = undef;
1030 return $localId;
1031 }
1032  
1033 sub DoEnterLogin {
1034 $wikiTemplate->vars(&globalTemplateVars);
1035 print GetHttpHeader() . $wikiTemplate->process('login');
1036 }
1037  
1038 sub DoLogin {
1039 my $success = 0;
1040 my $username = &GetParam("p_username", "");
1041 my $password = &GetParam("p_password", "");
1042 $password = '' if ($password eq '*');
1043  
1044 my $userId = $userDb->idFromUsername($username);
1045 $user = $userDb->loadUser($userId);
1046 if ($user && defined($user->getField('password')) &&
1047 ($user->getField('password') eq $password)) {
1048 $session->param('userId', $userId);
1049 $success = 1;
1050 }
1051 else {
1052 $user = undef;
1053 }
1054 $wikiTemplate->vars(&globalTemplateVars,
1055 loginSuccess => $success);
1056 print GetHttpHeader() . $wikiTemplate->process('loginResults');
1057 }
1058  
1059 sub DoLogout {
1060 if ($config->UseINames && (my $xsid = $session->param('xsid')) ) {
1061 my $spit = XDI::SPIT->new;
1062 my $iname = $user->username;
1063 my ($idBroker, $inumber) = $spit->resolveBroker($iname);
1064 $spit->logout($idBroker, $iname, $xsid) if ($idBroker);
1065 }
1066 $session->delete;
1067 my $cookie = $q->cookie(-name => $config->SiteName,
1068 -value => '',
1069 -path => '/cgi-bin/',
1070 -expires => '-1d');
1071 my $header;
1072 if ($config->HttpCharset ne '') {
1073 $header = $q->header(-cookie=>$cookie,
1074 -type=>"text/html; charset=" . $config->HttpCharset);
1075 }
1076 $header = $q->header(-cookie=>$cookie);
1077 $wikiTemplate->vars(&globalTemplateVars,
1078 userName => undef,
1079 prevUserName => $user->username);
1080 $user = undef;
1081 print $header . $wikiTemplate->process('logout');
1082 }
1083  
1084 sub DoGetIname {
1085 my $localId = &CreateNewUser if (!$user);
1086 my $spname = $config->ServiceProviderName;
1087 my $spkey = $config->ServiceProviderKey;
1088 my $rtnUrl = $config->ReturnUrl;
1089 my $rsid = &Digest::MD5::md5_hex("$localId$spkey");
1090 print "Location: http://dev.idcommons.net/register.html?registry=$spname&local_id=$localId&rsid=$rsid&rtn=$rtnUrl\n\n";
1091 }
1092  
1093 sub DoAssociateIname {
1094 my ($iname, $localId, $rrsid) = @_;
1095  
1096 if ( $rrsid = &Digest::MD5::md5_hex($localId . $config->ServiceProviderKey . 'x') &&
1097 (!$user) ) {
1098 # associate i-name with ID
1099 $user = $userDb->loadUser($localId);
1100 $user->username($iname);
1101 $userDb->saveUser($user);
1102 # now login
1103 my $spit = XDI::SPIT->new;
1104 my ($idBroker, $inumber) = $spit->resolveBroker($iname);
1105 if ($idBroker) {
1106 my $redirectUrl = $spit->getAuthUrl($idBroker, $iname, $config->ReturnUrl);
1107 print "Location: $redirectUrl\n\n";
1108 }
1109 else {
1110 $wikiTemplate->vars(&globalTemplateVars);
1111 print &GetHttpHeader . $wikiTemplate->process('errors/inameInvalid');
1112 }
1113 }
1114 else {
1115 if ($user) {
1116 print STDERR "NOT GUEST USER\n";
1117 }
1118 $wikiTemplate->vars(&globalTemplateVars);
1119 print &GetHttpHeader . $wikiTemplate->process('errors/badInameRegistration');
1120 }
1121 }
1122  
1123 sub DoIname {
1124 my ($iname, $xsid) = @_;
1125  
1126 my $spit = XDI::SPIT->new;
1127 my ($idBroker, $inumber) = $spit->resolveBroker($iname);
1128 if ($idBroker) {
1129 if ($xsid) {
1130 if ($spit->validateSession($idBroker, $iname, $xsid)) {
1131 $session->param('xsid', $xsid);
1132 my $userId = $userDb->idFromUsername($iname);
1133 if ($userId) {
1134 $user = $userDb->loadUser($userId);
1135 $session->param('userId', $userId);
1136 }
1137 else { # create new account
1138 &DoNewLogin;
1139 $user->username($iname);
1140 $userDb->saveUser($user);
1141 }
1142 # successful login message
1143 $wikiTemplate->vars(&globalTemplateVars,
1144 loginSuccess => 1);
1145 print &GetHttpHeader . $wikiTemplate->process('loginResults');
1146 }
1147 else { # invalid xsid
1148 $wikiTemplate->vars(&globalTemplateVars);
1149 print &GetHttpHeader . $wikiTemplate->process('errors/xsidInvalid');
1150 }
1151 }
1152 else {
1153 my $redirectUrl = $spit->getAuthUrl($idBroker, $iname, $config->ReturnUrl);
1154 print "Location: $redirectUrl\n\n";
1155 }
1156 }
1157 else { # i-name didn't resolve
1158 $wikiTemplate->vars(&globalTemplateVars);
1159 print &GetHttpHeader . $wikiTemplate->process('errors/inameInvalid');
1160 }
1161 }
1162  
1163 sub DoSearch {
1164 my ($string) = @_;
1165  
1166 if ($string eq '') {
1167 DoIndex();
1168 return;
1169 }
1170 # do the new pluggable search
1171 my $search = new PurpleWiki::Search::Engine(config => $config);
1172 $search->search($string);
1173  
1174 $wikiTemplate->vars(&globalTemplateVars,
1175 keywords => $string,
1176 modules => $search->modules,
1177 results => $search->results);
1178 print GetHttpHeader() . $wikiTemplate->process('searchResults');
1179 }
1180  
1181 sub DoPost {
1182 my ($editDiff, $old, $newAuthor, $pgtime, $oldrev, $preview);
1183 my $userName = $user ? $user->username : undef;
1184 my $userId = $user ? $user->id : undef;
1185 my $string = GetParam("text", undef);
1186 my $id = GetParam("title", "");
1187 my $summary = GetParam("summary", "");
1188 my $oldtime = GetParam("oldtime", "");
1189 my $oldconflict = GetParam("oldconflict", "");
1190 my $isEdit = 0;
1191 my $editTime = $Now;
1192 my $authorAddr = $ENV{REMOTE_ADDR};
1193  
1194 my $fsexp = $config->FS;
1195  
1196 # adjust the contents of $string with the wiki drivers to save purple
1197 # numbers
1198  
1199 # clean \r out of string
1200 $string =~ s/\r//g;
1201  
1202 my $url = $q->url() . "?$id";
1203 my $wiki = $wikiParser->parse($string,
1204 'add_node_ids'=>1,
1205 'url'=>$url,
1206 'freelink' => $config->FreeLinks);
1207 my $output = $wiki->view('wikitext');
1208  
1209 $string = $output;
1210  
1211 # clean \r out of string
1212 $string =~ s/\r//g;
1213  
1214 $wikiTemplate->vars(&globalTemplateVars,
1215 pageName => $id);
1216 if (!$acl->canEdit($user, $id)) {
1217 # This is an internal interface--we don't need to explain
1218 print GetHttpHeader() . $wikiTemplate->process('errors/editNotAllowed');
1219 return;
1220 }
1221  
1222 if (($id eq 'SampleUndefinedPage') || ($id eq 'SampleUndefinedPage')) {
1223 print GetHttpHeader() . $wikiTemplate->process('errors/pageCannotBeDefined');
1224 return;
1225 }
1226 if (($id eq 'Sample_Undefined_Page')
1227 || ($id eq 'Sample_Undefined_Page')) {
1228 print GetHttpHeader() . $wikiTemplate->process('errors/pageCannotBeDefined');
1229 return;
1230 }
1231 $string =~ s/$fsexp//g;
1232 $summary =~ s/$fsexp//g;
1233 $summary =~ s/[\r\n]//g;
1234 # Add a newline to the end of the string (if it doesn't have one)
1235 $string .= "\n" if (!($string =~ /\n$/));
1236  
1237 # Lock before getting old page to prevent races
1238 PurpleWiki::Database::RequestLock() or die('Could not get editing lock');
1239 # Consider extracting lock section into sub, and eval-wrap it?
1240 # (A few called routines can die, leaving locks.)
1241 my $keptRevision = new PurpleWiki::Database::KeptRevision(id => $id);
1242 my $page = new PurpleWiki::Database::Page('id' => $id, 'now' => $Now);
1243 $page->openPage();
1244 my $text = $page->getText();
1245 my $section = $page->getSection();
1246 $old = $text->getText();
1247 $oldrev = $section->getRevision();
1248 $pgtime = $section->getTS();
1249  
1250 $preview = 0;
1251 $preview = 1 if (GetParam("Preview", "") ne "");
1252 if (!$preview && ($old eq $string)) { # No changes (ok for preview)
1253 PurpleWiki::Database::ReleaseLock();
1254 ReBrowsePage($id, "", 1);
1255 return;
1256 }
1257 # Later extract comparison?
1258 if ($user || ($section->getID() > 399)) {
1259 $newAuthor = ($user->id ne $section->getID()); # known user(s)
1260 } else {
1261 $newAuthor = ($section->getIP() ne $authorAddr); # hostname fallback
1262 }
1263 $newAuthor = 1 if ($oldrev == 0); # New page
1264 $newAuthor = 0 if (!$newAuthor); # Standard flag form, not empty
1265 # Detect editing conflicts and resubmit edit
1266 if (($oldrev > 0) && ($newAuthor && ($oldtime != $pgtime))) {
1267 PurpleWiki::Database::ReleaseLock();
1268 if ($oldconflict>0) { # Conflict again...
1269 DoEdit($id, 2, $pgtime, $string, $preview);
1270 } else {
1271 DoEdit($id, 1, $pgtime, $string, $preview);
1272 }
1273 return;
1274 }
1275 if ($preview) {
1276 PurpleWiki::Database::ReleaseLock();
1277 DoEdit($id, 0, $pgtime, $string, 1);
1278 return;
1279 }
1280  
1281 # If the person doing editing chooses, send out email notification
1282 if (GetParam("recent_edit", "") eq 'on') {
1283 $isEdit = 1;
1284 }
1285 if (!$isEdit) {
1286 $page->setPageCache('oldmajor', $section->getRevision());
1287 }
1288 if ($newAuthor) {
1289 $page->setPageCache('oldauthor', $section->getRevision());
1290 }
1291  
1292 # I removed the if statement and moved the 3 lines of code down below
1293 # -matthew
1294 #
1295 # only save section if it is not the first
1296 #if ($section->getRevision() > 0) {
1297 # $keptRevision->addSection($section, $Now);
1298 # $keptRevision->trimKepts($Now);
1299 # $keptRevision->save();
1300 #}
1301  
1302 if ($config->UseDiff) {
1303 # FIXME: how many args does it take to screw a pooch?
1304 PurpleWiki::Database::UpdateDiffs($page, $keptRevision, $id, $editTime, $old, $string, $isEdit, $newAuthor);
1305 }
1306 $text->setText($string);
1307 $text->setMinor($isEdit);
1308 $text->setNewAuthor($newAuthor);
1309 $text->setSummary($summary);
1310 $section->setHost(GetRemoteHost(1));
1311 # FIXME: redundancy in data structure here
1312 $section->setRevision($section->getRevision() + 1);
1313 $section->setTS($Now);
1314 $section->setUsername($userName);
1315 $section->setID($userId);
1316 $keptRevision->addSection($section, $Now);
1317 $keptRevision->trimKepts($Now);
1318 $keptRevision->save();
1319 $page->setRevision($section->getRevision());
1320 $page->setTS($Now);
1321 $page->save();
1322 &WriteRcLog($id, $summary, $isEdit, $editTime, $userName, $section->getHost());
1323 &PurpleWiki::Database::ReleaseLock();
1324 &ReBrowsePage($id, "", 1);
1325 }
1326  
1327 # Note: all diff and recent-list operations should be done within locks.
1328 sub DoUnlock {
1329 my $forcedUnlock = 0;
1330  
1331 if (PurpleWiki::Database::ForceReleaseLock('main', $config)) {
1332 $forcedUnlock = 1;
1333 }
1334 # Later display status of other locks?
1335 PurpleWiki::Database::ForceReleaseLock('cache', $config);
1336 PurpleWiki::Database::ForceReleaseLock('diff', $config);
1337 PurpleWiki::Database::ForceReleaseLock('index', $config);
1338 $wikiTemplate->vars(&globalTemplateVars,
1339 forcedUnlock => $forcedUnlock);
1340 print GetHttpHeader() . $wikiTemplate->process('removeEditLock');
1341  
1342 }
1343  
1344 # Note: all diff and recent-list operations should be done within locks.
1345 sub WriteRcLog {
1346 my ($id, $summary, $isEdit, $editTime, $name, $rhost) = @_;
1347 my ($extraTemp, %extra);
1348  
1349 %extra = ();
1350 $extra{'id'} = $user->id if ($user);
1351 $extra{'name'} = $name if ($name ne "");
1352 $extraTemp = join($config->FS2, %extra);
1353 # The two fields at the end of a line are kind and extension-hash
1354 my $rc_line = join($config->FS3, $editTime, $id, $summary,
1355 $isEdit, $rhost, "0", $extraTemp);
1356 my $rc_file = $config->RcFile;
1357 if (!open(OUT, ">>$rc_file")) {
1358 die($config->RCName . " log error: $!");
1359 }
1360 print OUT $rc_line . "\n";
1361 close(OUT);
1362 }
1363  
1364 # ==== Difference markup and HTML ====
1365 sub DoDiff {
1366 my ($page, $keptRevision, $diffType, $id, $pageName, $lastEdited,
1367 $rev, $newText) = @_;
1368 my $cacheName;
1369 my $diffText;
1370 my $diffTypeString;
1371 my @diffLinks;
1372 my $noDiff = 0;
1373  
1374 my $useMajor = 1;
1375 my $useMinor = 1;
1376 my $useAuthor = 1;
1377 if ($diffType == 1) {
1378 $diffTypeString = 'major';
1379 $cacheName = 'major';
1380 $useMajor = 0;
1381 }
1382 elsif ($diffType == 2) {
1383 $diffTypeString = 'minor';
1384 $cacheName = 'minor';
1385 $useMinor = 0;
1386 }
1387 elsif ($diffType == 3) {
1388 $diffTypeString = 'author';
1389 $cacheName = 'author';
1390 $useAuthor = 0;
1391 }
1392 if ($rev ne "") {
1393 $diffText = PurpleWiki::Database::GetKeptDiff($keptRevision,
1394 $newText, $rev, 1); # 1 = get lock
1395 if ($diffText eq "") {
1396 $diffText = '(The revisions are identical or unavailable.)';
1397 }
1398 }
1399 else {
1400 $diffText = PurpleWiki::Database::GetCacheDiff($page, $cacheName);
1401 }
1402 $useMajor = 0
1403 if ($useMajor && ($diffText eq PurpleWiki::Database::GetCacheDiff($page, "major")));
1404 $useMinor = 0
1405 if ($useMinor && ($diffText eq PurpleWiki::Database::GetCacheDiff($page, "minor")));
1406 $useAuthor = 0
1407 if ($useAuthor && ($diffText eq PurpleWiki::Database::GetCacheDiff($page, "author")));
1408 $useMajor = 0
1409 if ((!defined($page->getPageCache('oldmajor'))) ||
1410 ($page->getPageCache("oldmajor") < 1));
1411 $useAuthor = 0
1412 if ((!defined($page->getPageCache('oldauthor'))) ||
1413 ($page->getPageCache("oldauthor") < 1));
1414 push @diffLinks, { type => 'major', url => $config->ScriptName . "?action=browse&amp;diff=1&amp;id=$id" }
1415 if ($useMajor);
1416 push @diffLinks, { type => 'minor', url => $config->ScriptName . "?action=browse&amp;diff=2&amp;id=$id" }
1417 if ($useMinor);
1418 push @diffLinks, { type => 'author', url => $config->ScriptName . "?action=browse&amp;diff=3&amp;id=$id" }
1419 if ($useAuthor);
1420 if (($rev eq '') && ($diffType != 2) &&
1421 ((!defined($page->getPageCache("old$cacheName"))) ||
1422 ($page->getPageCache("old$cacheName") < 1))) {
1423 $noDiff = 1;
1424 }
1425 $wikiTemplate->vars(&globalTemplateVars,
1426 pageName => $pageName,
1427 revision => $rev,
1428 diffType => $diffTypeString,
1429 diffLinks => \@diffLinks,
1430 nodiff => $noDiff,
1431 diffs => getDiffs($diffText),
1432 lastEdited => $lastEdited,
1433 pageUrl => $config->ScriptName . "?$id",
1434 backlinksUrl => $config->ScriptName . "?search=$id",
1435 revisionsUrl => $config->ScriptName . "?action=history&amp;id=$id");
1436 print GetHttpHeader() . $wikiTemplate->process('viewDiff');
1437 }
1438  
1439 # @diffs = ( { type => (status|removed|added), text => [] }, ... )
1440 sub getDiffs {
1441 my $diffText = shift;
1442 my @diffs;
1443  
1444 my $added;
1445 my $removed;
1446 foreach my $line (split /\n/, $diffText) {
1447 my $statusMessage;
1448 if ($line =~ /^(\d+.*[adc].*)/) {
1449 my $statusMessage = $1;
1450 my $statusType;
1451 if ($statusMessage =~ /a/) {
1452 $statusType = 'Added: ';
1453 }
1454 elsif ($statusMessage =~ /d/) {
1455 $statusType = 'Removed: ';
1456 }
1457 else {
1458 $statusType = 'Changed: ';
1459 }
1460 if ($added) {
1461 $added = QuoteHtml($added);
1462 $added =~ s/\n/<br \/>\n/sg;
1463 push @diffs, { type => 'added', text => $added };
1464 $added = '';
1465 }
1466 elsif ($removed) {
1467 $removed = QuoteHtml($removed);
1468 $removed =~ s/\n/<br \/>\n/sg;
1469 push @diffs, { type => 'removed', text => $removed };
1470 $removed = '';
1471 }
1472 push @diffs, { type => 'status', text => "$statusType$statusMessage" };
1473 }
1474 elsif ($line =~ /^</) { # removed
1475 if ($added) {
1476 $added = QuoteHtml($added);
1477 $added =~ s/\n/<br \/>\n/sg;
1478 push @diffs, { type => 'added', text => $added };
1479 $added = '';
1480 }
1481 $line =~ s/^< //;
1482 $removed .= "$line\n";
1483 }
1484 elsif ($line =~ /^>/) { # added
1485 if ($removed) {
1486 $removed = QuoteHtml($removed);
1487 $removed =~ s/\n/<br \/>\n/sg;
1488 push @diffs, { type => 'removed', text => $removed };
1489 $removed = '';
1490 }
1491 $line =~ s/^> //;
1492 $added .= "$line\n";
1493 }
1494 }
1495 if ($added) {
1496 $added = QuoteHtml($added);
1497 $added =~ s/\n/<br \/>\n/sg;
1498 push @diffs, { type => 'added', text => $added };
1499 $added = '';
1500 }
1501 elsif ($removed) {
1502 $removed = QuoteHtml($removed);
1503 $removed =~ s/\n/<br \/>\n/sg;
1504 push @diffs, { type => 'removed', text => $removed };
1505 $removed = '';
1506 }
1507 return \@diffs;
1508 }
1509  
1510 sub logSession {
1511 open FH, ">>$CONFIG_DIR/session_log";
1512 print FH time . "\t" . $session->id . "\t" . $q->request_method . "\t";
1513 print FH $q->query_string if ($q->request_method ne 'POST');
1514 print FH "\t" . $q->remote_host . "\t" . $session->param('userId') . "\t" .
1515 $q->referer . "\n";
1516 close FH;
1517 }
1518  
1519 sub updateVisitedPagesCache {
1520 my $id = shift;
1521  
1522 my @pages = keys %{$visitedPagesCache};
1523 if (!defined $visitedPagesCache->{$id} &&
1524 (scalar @pages - 1 >= $visitedPagesCacheSize)) {
1525 my @oldestPages = sort {
1526 $visitedPagesCache->{$a} <=> $visitedPagesCache->{$b}
1527 } @pages;
1528 my $remove = scalar @pages - $visitedPagesCacheSize + 1;
1529 for (my $i = 0; $i < $remove; $i++) {
1530 delete $visitedPagesCache->{$oldestPages[$i]};
1531 }
1532 }
1533 $visitedPagesCache->{$id} = time;
1534 $session->param('visitedPagesCache', $visitedPagesCache);
1535 }
1536  
1537 sub visitedPages {
1538 my @pages = sort { $visitedPagesCache->{$b} <=> $visitedPagesCache->{$a} }
1539 keys %{$visitedPagesCache};
1540 my $i = 0;
1541 foreach my $id (@pages) {
1542 my $pageName = $id;
1543 $pageName =~ s/_/ /g if ($config->FreeLinks);
1544 $pages[$i] = {
1545 'id' => $id,
1546 'pageName' => $pageName,
1547 };
1548 $i++;
1549 };
1550 return @pages;
1551 }
1552  
1553 sub expandPageName {
1554 my $pageName = shift;
1555  
1556 if ($pageName !~ / /) {
1557 $pageName =~ s/([a-z])([A-Z])/$1 $2/g;
1558 $pageName =~ s/([0-9])([A-Z])/$1 $2/g;
1559 $pageName =~ s/([a-z])([0-9])/$1 $2/g;
1560 }
1561 return $pageName;
1562 }
1563  
1564 sub globalTemplateVars {
1565 return (siteName => $config->SiteName,
1566 baseUrl => $config->ScriptName,
1567 homePage => $config->HomePage,
1568 userName => $user ? $user->username : undef,
1569 preferencesUrl => $config->ScriptName . '?action=editprefs');
1570 }
1571  
1572 &DoWikiRequest() if ($config->RunCGI && ($_ ne 'nocgi')); # Do everything.
1573 1; # In case we are loaded from elsewhere
1574 # == End of UseModWiki script. ===========================================