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