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