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