* Patch from Ethan to improve behavior if a page is deleted or moved while
[ikiwiki.git] / IkiWiki / CGI.pm
1 #!/usr/bin/perl
2
3 use warnings;
4 use strict;
5 use IkiWiki;
6 use IkiWiki::UserInfo;
7 use open qw{:utf8 :std};
8 use Encode;
9
10 package IkiWiki;
11
12 sub printheader ($) { #{{{
13         my $session=shift;
14         
15         if ($config{sslcookie}) {
16                 print $session->header(-charset => 'utf-8',
17                         -cookie => $session->cookie(-secure => 1));
18         } else {
19                 print $session->header(-charset => 'utf-8');
20         }
21
22 } #}}}
23
24 sub redirect ($$) { #{{{
25         my $q=shift;
26         my $url=shift;
27         if (! $config{w3mmode}) {
28                 print $q->redirect($url);
29         }
30         else {
31                 print "Content-type: text/plain\n";
32                 print "W3m-control: GOTO $url\n\n";
33         }
34 } #}}}
35
36 sub check_canedit ($$$;$) { #{{{
37         my $page=shift;
38         my $q=shift;
39         my $session=shift;
40         my $nonfatal=shift;
41         
42         my $canedit;
43         run_hooks(canedit => sub {
44                 return if defined $canedit;
45                 my $ret=shift->($page, $q, $session);
46                 if (defined $ret && $ret eq "") {
47                         $canedit=1;
48                 }
49                 elsif (defined $ret) {
50                         $canedit=0;
51                         error($ret) unless $nonfatal;
52                 }
53         });
54         return $canedit;
55 } #}}}
56
57 sub decode_form_utf8 ($) { #{{{
58         my $form = shift;
59         foreach my $f ($form->field) {
60                 next if Encode::is_utf8(scalar $form->field($f));
61                 $form->field(name  => $f,
62                              value => decode_utf8($form->field($f)),
63                              force => 1,
64                             );
65         }
66 } #}}}
67
68 sub cgi_recentchanges ($) { #{{{
69         my $q=shift;
70         
71         # Optimisation: building recentchanges means calculating lots of
72         # links. Memoizing htmllink speeds it up a lot (can't be memoized
73         # during page builds as the return values may change, but they
74         # won't here.)
75         eval q{use Memoize};
76         error($@) if $@;
77         memoize("htmllink");
78
79         eval q{use Time::Duration};
80         error($@) if $@;
81
82         my $changelog=[rcs_recentchanges(100)];
83         foreach my $change (@$changelog) {
84                 $change->{when} = concise(ago($change->{when}));
85
86                 $change->{user} = userlink($change->{user});
87
88                 my $is_excess = exists $change->{pages}[10]; # limit pages to first 10
89                 delete @{$change->{pages}}[10 .. @{$change->{pages}}] if $is_excess;
90                 $change->{pages} = [
91                         map {
92                                 $_->{link} = htmllink("", "", $_->{page},
93                                         noimageinline => 1,
94                                         linktext => pagetitle($_->{page}));
95                                 $_;
96                         } @{$change->{pages}}
97                 ];
98                 push @{$change->{pages}}, { link => '...' } if $is_excess;
99         }
100
101         my $template=template("recentchanges.tmpl"); 
102         $template->param(
103                 title => "RecentChanges",
104                 indexlink => indexlink(),
105                 wikiname => $config{wikiname},
106                 changelog => $changelog,
107                 baseurl => baseurl(),
108         );
109         run_hooks(pagetemplate => sub {
110                 shift->(page => "", destpage => "", template => $template);
111         });
112         print $q->header(-charset => 'utf-8'), $template->output;
113 } #}}}
114
115 # Check if the user is signed in. If not, redirect to the signin form and
116 # save their place to return to later.
117 sub needsignin ($$) { #{{{
118         my $q=shift;
119         my $session=shift;
120
121         if (! defined $session->param("name") ||
122             ! userinfo_get($session->param("name"), "regdate")) {
123                 if (! defined $session->param("postsignin")) {
124                         $session->param(postsignin => $ENV{QUERY_STRING});
125                 }
126                 cgi_signin($q, $session);
127                 cgi_savesession($session);
128                 exit;
129         }
130 } #}}}  
131
132 sub cgi_signin ($$) { #{{{
133         my $q=shift;
134         my $session=shift;
135
136         eval q{use CGI::FormBuilder};
137         error($@) if $@;
138         my $form = CGI::FormBuilder->new(
139                 title => "signin",
140                 header => 1,
141                 charset => "utf-8",
142                 method => 'POST',
143                 required => 'NONE',
144                 javascript => 0,
145                 params => $q,
146                 action => $config{cgiurl},
147                 header => 0,
148                 template => scalar template_params("signin.tmpl"),
149                 stylesheet => baseurl()."style.css",
150         );
151         my $buttons=["Login"];
152         
153         if ($q->param("do") ne "signin" && !$form->submitted) {
154                 $form->text(gettext("You need to log in first."));
155         }
156         $form->field(name => "do", type => "hidden", value => "signin",
157                 force => 1);
158         
159         run_hooks(formbuilder_setup => sub {
160                 shift->(form => $form, cgi => $q, session => $session);
161         });
162         
163         decode_form_utf8($form);
164
165         if (exists $hooks{formbuilder}) {
166                 run_hooks(formbuilder => sub {
167                         shift->(form => $form, cgi => $q, session => $session,
168                                 buttons => $buttons);
169                 });
170         }
171         else {
172                 if ($form->submitted) {
173                         $form->validate;
174                 }
175                 printheader($session);
176                 print misctemplate($form->title, $form->render(submit => $buttons));
177         }
178 } #}}}
179
180 sub cgi_postsignin ($$) { #{{{
181         my $q=shift;
182         my $session=shift;
183         
184         # Continue with whatever was being done before the signin process.
185         if (defined $session->param("postsignin")) {
186                 my $postsignin=CGI->new($session->param("postsignin"));
187                 $session->clear("postsignin");
188                 cgi($postsignin, $session);
189                 cgi_savesession($session);
190                 exit;
191         }
192         else {
193                 # This can occur, for example, if a user went to the signin
194                 # url via a bookmark.
195                 redirect($q, $config{url});
196         }
197 } #}}}
198
199 sub cgi_prefs ($$) { #{{{
200         my $q=shift;
201         my $session=shift;
202
203         needsignin($q, $session);
204
205         eval q{use CGI::FormBuilder};
206         error($@) if $@;
207         my $form = CGI::FormBuilder->new(
208                 title => "preferences",
209                 header => 0,
210                 charset => "utf-8",
211                 method => 'POST',
212                 validate => {
213                         email => 'EMAIL',
214                 },
215                 required => 'NONE',
216                 javascript => 0,
217                 params => $q,
218                 action => $config{cgiurl},
219                 template => scalar template_params("prefs.tmpl"),
220                 stylesheet => baseurl()."style.css",
221         );
222         my $buttons=["Save Preferences", "Logout", "Cancel"];
223
224         run_hooks(formbuilder_setup => sub {
225                 shift->(form => $form, cgi => $q, session => $session);
226         });
227         
228         $form->field(name => "do", type => "hidden");
229         $form->field(name => "email", size => 50);
230         $form->field(name => "subscriptions", size => 50,
231                 comment => "(".htmllink("", "", "PageSpec", noimageinline => 1).")");
232         $form->field(name => "banned_users", size => 50);
233         
234         my $user_name=$session->param("name");
235         if (! is_admin($user_name)) {
236                 $form->field(name => "banned_users", type => "hidden");
237         }
238
239         if (! $form->submitted) {
240                 $form->field(name => "email", force => 1,
241                         value => userinfo_get($user_name, "email"));
242                 $form->field(name => "subscriptions", force => 1,
243                         value => userinfo_get($user_name, "subscriptions"));
244                 if (is_admin($user_name)) {
245                         $form->field(name => "banned_users", force => 1,
246                                 value => join(" ", get_banned_users()));
247                 }
248         }
249         
250         decode_form_utf8($form);
251         
252         if ($form->submitted eq 'Logout') {
253                 $session->delete();
254                 redirect($q, $config{url});
255                 return;
256         }
257         elsif ($form->submitted eq 'Cancel') {
258                 redirect($q, $config{url});
259                 return;
260         }
261         elsif ($form->submitted eq 'Save Preferences' && $form->validate) {
262                 foreach my $field (qw(email subscriptions)) {
263                         if (defined $form->field($field) && length $form->field($field)) {
264                                 userinfo_set($user_name, $field, $form->field($field)) ||
265                                         error("failed to set $field");
266                         }
267                 }
268                 if (is_admin($user_name)) {
269                         set_banned_users(grep { ! is_admin($_) }
270                                         split(' ',
271                                                 $form->field("banned_users"))) ||
272                                 error("failed saving changes");
273                 }
274                 $form->text(gettext("Preferences saved."));
275         }
276         
277         if (exists $hooks{formbuilder}) {
278                 run_hooks(formbuilder => sub {
279                         shift->(form => $form, cgi => $q, session => $session,
280                                 buttons => $buttons);
281                 });
282         }
283         else {
284                 printheader($session);
285                 print misctemplate($form->title, $form->render(submit => $buttons));
286         }
287 } #}}}
288
289 sub cgi_editpage ($$) { #{{{
290         my $q=shift;
291         my $session=shift;
292
293         my @fields=qw(do rcsinfo subpage from page type editcontent comments
294                       newfile);
295         my @buttons=("Save Page", "Preview", "Cancel");
296         
297         eval q{use CGI::FormBuilder};
298         error($@) if $@;
299         my $form = CGI::FormBuilder->new(
300                 fields => \@fields,
301                 header => 1,
302                 charset => "utf-8",
303                 method => 'POST',
304                 validate => {
305                         editcontent => '/.+/',
306                 },
307                 required => [qw{editcontent}],
308                 javascript => 0,
309                 params => $q,
310                 action => $config{cgiurl},
311                 table => 0,
312                 template => scalar template_params("editpage.tmpl"),
313         );
314         
315         run_hooks(formbuilder_setup => sub {
316                 shift->(form => $form, cgi => $q, session => $session);
317         });
318         
319         decode_form_utf8($form);
320         
321         # This untaint is safe because titlepage removes any problematic
322         # characters.
323         my ($page)=$form->field('page');
324         $page=titlepage(possibly_foolish_untaint($page));
325         if (! defined $page || ! length $page || file_pruned($page, $config{srcdir}) || $page=~/^\//) {
326                 error("bad page name");
327         }
328         
329         my $from;
330         if (defined $form->field('from')) {
331                 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
332         }
333         
334         my $file;
335         my $type;
336         if (exists $pagesources{$page}) {
337                 $file=$pagesources{$page};
338                 $type=pagetype($file);
339                 if (! defined $type) {
340                         error(sprintf(gettext("%s is not an editable page"), $page));
341                 }
342         }
343         else {
344                 $type=$form->param('type');
345                 if (defined $type && length $type && $hooks{htmlize}{$type}) {
346                         $type=possibly_foolish_untaint($type);
347                 }
348                 elsif (defined $from) {
349                         # favor the type of linking page
350                         $type=pagetype($pagesources{$from});
351                 }
352                 $type=$config{default_pageext} unless defined $type;
353                 $file=$page.".".$type;
354         }
355
356
357         $form->field(name => "do", type => 'hidden');
358         $form->field(name => "from", type => 'hidden');
359         $form->field(name => "rcsinfo", type => 'hidden');
360         $form->field(name => "subpage", type => 'hidden');
361         $form->field(name => "page", value => $page, force => 1);
362         $form->field(name => "type", value => $type, force => 1);
363         $form->field(name => "comments", type => "text", size => 80);
364         $form->field(name => "editcontent", type => "textarea", rows => 20,
365                 cols => 80);
366         $form->field(name => "newfile", type => 'hidden');
367         $form->tmpl_param("can_commit", $config{rcs});
368         $form->tmpl_param("indexlink", indexlink());
369         $form->tmpl_param("helponformattinglink",
370                 htmllink("", "", "HelpOnFormatting", noimageinline => 1));
371         $form->tmpl_param("baseurl", baseurl());
372         if (! $form->submitted) {
373                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
374                         force => 1);
375                 $form->field(name => "newfile", 
376                         value => ! -e "$config{srcdir}/$file",
377                         force => 1);
378         }
379         
380         if ($form->submitted eq "Cancel") {
381                 if ($form->field(name => "newfile") && defined $from) {
382                         redirect($q, "$config{url}/".htmlpage($from));
383                 }
384                 elsif ($form->field(name => "newfile")) {
385                         redirect($q, $config{url});
386                 }
387                 else {
388                         redirect($q, "$config{url}/".htmlpage($page));
389                 }
390                 return;
391         }
392         elsif ($form->submitted eq "Preview") {
393                 my $content=$form->field('editcontent');
394                 my $comments=$form->field('comments');
395                 $form->field(name => "editcontent",
396                                 value => $content, force => 1);
397                 $form->field(name => "comments",
398                                 value => $comments, force => 1);
399                 $config{rss}=$config{atom}=0; # avoid preview writing a feed!
400                 $form->tmpl_param("page_preview",
401                         htmlize($page, $type,
402                         linkify($page, "",
403                         preprocess($page, $page,
404                         filter($page, $content)))));
405         }
406         else {
407                 $form->tmpl_param("page_preview", "");
408         }
409         $form->tmpl_param("page_conflict", "");
410         
411         if (! $form->submitted || $form->submitted eq "Preview" || 
412             ! $form->validate) {
413                 if ($form->field("do") eq "create") {
414                         my @page_locs;
415                         my $best_loc;
416                         if (! defined $from || ! length $from ||
417                             $from ne $form->field('from') ||
418                             file_pruned($from, $config{srcdir}) ||
419                             $from=~/^\// ||
420                             $form->submitted eq "Preview") {
421                                 @page_locs=$best_loc=$page;
422                         }
423                         else {
424                                 my $dir=$from."/";
425                                 $dir=~s![^/]+/+$!!;
426                                 
427                                 if ((defined $form->field('subpage') && length $form->field('subpage')) ||
428                                     $page eq gettext('discussion')) {
429                                         $best_loc="$from/$page";
430                                 }
431                                 else {
432                                         $best_loc=$dir.$page;
433                                 }
434                                 
435                                 push @page_locs, $dir.$page;
436                                 push @page_locs, "$from/$page";
437                                 while (length $dir) {
438                                         $dir=~s![^/]+/+$!!;
439                                         push @page_locs, $dir.$page;
440                                 }
441                         }
442                         push @page_locs, "$config{userdir}/$page"
443                                 if length $config{userdir};
444
445                         @page_locs = grep {
446                                 ! exists $pagecase{lc $_}
447                         } @page_locs;
448                         if (! @page_locs) {
449                                 # hmm, someone else made the page in the
450                                 # meantime?
451                                 redirect($q, "$config{url}/".htmlpage($page));
452                                 return;
453                         }
454
455                         my @editable_locs = grep {
456                                 check_canedit($_, $q, $session, 1)
457                         } @page_locs;
458                         if (! @editable_locs) {
459                                 # let it throw an error this time
460                                 map { check_canedit($_, $q, $session) } @page_locs;
461                         }
462                         
463                         my @page_types;
464                         if (exists $hooks{htmlize}) {
465                                 @page_types=keys %{$hooks{htmlize}};
466                         }
467                         
468                         $form->tmpl_param("page_select", 1);
469                         $form->field(name => "page", type => 'select',
470                                 options => { map { $_ => pagetitle($_, 1) } @editable_locs },
471                                 value => $best_loc);
472                         $form->field(name => "type", type => 'select',
473                                 options => \@page_types);
474                         $form->title(sprintf(gettext("creating %s"), pagetitle($page)));
475                 }
476                 elsif ($form->field("do") eq "edit") {
477                         check_canedit($page, $q, $session);
478                         if (! defined $form->field('editcontent') || 
479                             ! length $form->field('editcontent')) {
480                                 my $content="";
481                                 if (exists $pagesources{$page}) {
482                                         $content=readfile(srcfile($pagesources{$page}));
483                                         $content=~s/\n/\r\n/g;
484                                 }
485                                 $form->field(name => "editcontent", value => $content,
486                                         force => 1);
487                         }
488                         $form->tmpl_param("page_select", 0);
489                         $form->field(name => "page", type => 'hidden');
490                         $form->field(name => "type", type => 'hidden');
491                         $form->title(sprintf(gettext("editing %s"), pagetitle($page)));
492                 }
493                 
494                 print $form->render(submit => \@buttons);
495         }
496         else {
497                 # save page
498                 check_canedit($page, $q, $session);
499                 if (! -e "$config{srcdir}/$file" && ! $form->field(name => 'newfile')){
500                         $form->tmpl_param("page_gone", 1);
501                         $form->field(name => "newfile",
502                                      value => 1, force => 1);
503                         $form->tmpl_param("page_select", 0);
504                         $form->field(name => "page", type => 'hidden');
505                         $form->field(name => "type", type => 'hidden');
506                         print $form->render(submit => \@buttons);
507                         return;
508                 }
509                 
510                 my $content=$form->field('editcontent');
511
512                 $content=~s/\r\n/\n/g;
513                 $content=~s/\r/\n/g;
514
515                 $config{cgi}=0; # avoid cgi error message
516                 eval { writefile($file, $config{srcdir}, $content) };
517                 $config{cgi}=1;
518                 if ($@) {
519                         $form->field(name => "rcsinfo", value => rcs_prepedit($file),
520                                 force => 1);
521                         $form->tmpl_param("failed_save", 1);
522                         $form->tmpl_param("error_message", $@);
523                         $form->field("editcontent", value => $content, force => 1);
524                         $form->tmpl_param("page_select", 0);
525                         $form->field(name => "page", type => 'hidden');
526                         $form->field(name => "type", type => 'hidden');
527                         $form->title(sprintf(gettext("editing %s"), $page));
528                         print $form->render(submit => \@buttons);
529                         return;
530                 }
531                 
532                 my $conflict;
533                 if ($config{rcs}) {
534                         my $message="";
535                         if (defined $form->field('comments') &&
536                             length $form->field('comments')) {
537                                 $message=$form->field('comments');
538                         }
539                         
540                         if ($form->field(name => "newfile")) {
541                                 rcs_add($file);
542                         }
543
544                         # Prevent deadlock with post-commit hook by
545                         # signaling to it that it should not try to
546                         # do anything (except send commit mails).
547                         disable_commit_hook();
548                         $conflict=rcs_commit($file, $message,
549                                 $form->field("rcsinfo"),
550                                 $session->param("name"), $ENV{REMOTE_ADDR});
551                         enable_commit_hook();
552                         rcs_update();
553                 }
554                 
555                 # Refresh even if there was a conflict, since other changes
556                 # may have been committed while the post-commit hook was
557                 # disabled.
558                 require IkiWiki::Render;
559                 refresh();
560                 saveindex();
561
562                 if (defined $conflict) {
563                         $form->field(name => "rcsinfo", value => rcs_prepedit($file),
564                                 force => 1);
565                         $form->tmpl_param("page_conflict", 1);
566                         $form->field("editcontent", value => $conflict, force => 1);
567                         $form->field("do", "edit", force => 1);
568                         $form->tmpl_param("page_select", 0);
569                         $form->field(name => "page", type => 'hidden');
570                         $form->field(name => "type", type => 'hidden');
571                         $form->title(sprintf(gettext("editing %s"), $page));
572                         print $form->render(submit => \@buttons);
573                         return;
574                 }
575                 else {
576                         # The trailing question mark tries to avoid broken
577                         # caches and get the most recent version of the page.
578                         redirect($q, "$config{url}/".htmlpage($page)."?updated");
579                 }
580         }
581 } #}}}
582
583 sub cgi_getsession ($) { #{{{
584         my $q=shift;
585
586         eval q{use CGI::Session};
587         CGI::Session->name("ikiwiki_session_".encode_utf8($config{wikiname}));
588         
589         my $oldmask=umask(077);
590         my $session = CGI::Session->new("driver:DB_File", $q,
591                 { FileName => "$config{wikistatedir}/sessions.db" });
592         umask($oldmask);
593
594         return $session;
595 } #}}}
596
597 sub cgi_savesession ($) { #{{{
598         my $session=shift;
599
600         # Force session flush with safe umask.
601         my $oldmask=umask(077);
602         $session->flush;
603         umask($oldmask);
604 } #}}}
605
606 sub cgi (;$$) { #{{{
607         my $q=shift;
608         my $session=shift;
609
610         if (! $q) {
611                 eval q{use CGI};
612                 error($@) if $@;
613         
614                 $q=CGI->new;
615         
616                 run_hooks(cgi => sub { shift->($q) });
617         }
618
619         my $do=$q->param('do');
620         if (! defined $do || ! length $do) {
621                 my $error = $q->cgi_error;
622                 if ($error) {
623                         error("Request not processed: $error");
624                 }
625                 else {
626                         error("\"do\" parameter missing");
627                 }
628         }
629         
630         # Things that do not need a session.
631         if ($do eq 'recentchanges') {
632                 cgi_recentchanges($q);
633                 return;
634         }
635         elsif ($do eq 'hyperestraier') {
636                 cgi_hyperestraier();
637         }
638
639         # Need to lock the wiki before getting a session.
640         lockwiki();
641         
642         if (! $session) {
643                 $session=cgi_getsession($q);
644         }
645         
646         # Auth hooks can sign a user in.
647         if ($do ne 'signin' && ! defined $session->param("name")) {
648                 run_hooks(auth => sub {
649                         shift->($q, $session)
650                 });
651                 if (defined $session->param("name")) {
652                         # Make sure whatever user was authed is in the
653                         # userinfo db.
654                         if (! userinfo_get($session->param("name"), "regdate")) {
655                                 userinfo_setall($session->param("name"), {
656                                         email => "",
657                                         password => "",
658                                         regdate => time,
659                                 }) || error("failed adding user");
660                         }
661                 }
662         }
663         
664         if (defined $session->param("name") &&
665             userinfo_get($session->param("name"), "banned")) {
666                 print $q->header(-status => "403 Forbidden");
667                 $session->delete();
668                 print gettext("You are banned.");
669                 cgi_savesession($session);
670         }
671         elsif ($do eq 'signin') {
672                 cgi_signin($q, $session);
673                 cgi_savesession($session);
674         }
675         elsif (defined $session->param("postsignin")) {
676                 cgi_postsignin($q, $session);
677         }
678         elsif ($do eq 'prefs') {
679                 cgi_prefs($q, $session);
680         }
681         elsif ($do eq 'create' || $do eq 'edit') {
682                 cgi_editpage($q, $session);
683         }
684         elsif ($do eq 'blog') {
685                 my $page=titlepage(decode_utf8($q->param('title')));
686                 $page=~s/(\/)/"__".ord($1)."__"/eg; # escape slashes too
687                 # if the page already exists, munge it to be unique
688                 my $from=$q->param('from');
689                 my $add="";
690                 while (exists $pagecase{lc "$from/$page$add"}) {
691                         $add=1 unless length $add;
692                         $add++;
693                 }
694                 $q->param('page', $page.$add);
695                 # now run same as create
696                 $q->param('do', 'create');
697                 cgi_editpage($q, $session);
698         }
699         elsif ($do eq 'postsignin') {
700                 error(gettext("login failed, perhaps you need to turn on cookies?"));
701         }
702         else {
703                 error("unknown do parameter");
704         }
705 } #}}}
706
707 sub userlink ($) { #{{{
708         my $user=shift;
709
710         eval q{use CGI 'escapeHTML'};
711         error($@) if $@;
712         if ($user =~ m!^https?://! &&
713             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
714                 # Munge user-urls, as used by eg, OpenID.
715                 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
716                 my $display=$oid->display;
717                 # Convert "user.somehost.com" to "user [somehost.com]".
718                 if ($display !~ /\[/) {
719                         $display=~s/^(.*?)\.([^.]+\.[a-z]+)$/$1 [$2]/;
720                 }
721                 # Convert "http://somehost.com/user" to "user [somehost.com]".
722                 if ($display !~ /\[/) {
723                         $display=~s/^https?:\/\/(.+)\/([^\/]+)$/$2 [$1]/;
724                 }
725                 $display=~s!^https?://!!; # make sure this is removed
726                 return "<a href=\"$user\">".escapeHTML($display)."</a>";
727         }
728         else {
729                 return htmllink("", "", escapeHTML(
730                         length $config{userdir} ? $config{userdir}."/".$user : $user
731                 ), noimageinline => 1);
732         }
733 } #}}}
734
735 1