web commit by http://jcflack.myopenid.com/
[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                 title => "editpage",
285                 fields => \@fields,
286                 charset => "utf-8",
287                 method => 'POST',
288                 required => [qw{editcontent}],
289                 javascript => 0,
290                 params => $q,
291                 action => $config{cgiurl},
292                 header => 0,
293                 table => 0,
294                 template => scalar template_params("editpage.tmpl"),
295                 wikiname => $config{wikiname},
296         );
297         
298         decode_form_utf8($form);
299         run_hooks(formbuilder_setup => sub {
300                 shift->(form => $form, cgi => $q, session => $session,
301                         buttons => \@buttons);
302         });
303         decode_form_utf8($form);
304         
305         # This untaint is safe because titlepage removes any problematic
306         # characters.
307         my ($page)=$form->field('page');
308         $page=titlepage(possibly_foolish_untaint($page));
309         if (! defined $page || ! length $page ||
310             file_pruned($page, $config{srcdir}) || $page=~/^\//) {
311                 error("bad page name");
312         }
313
314         my $baseurl=$config{url}."/".htmlpage($page);
315         
316         my $from;
317         if (defined $form->field('from')) {
318                 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
319         }
320         
321         my $file;
322         my $type;
323         if (exists $pagesources{$page} && $form->field("do") ne "create") {
324                 $file=$pagesources{$page};
325                 $type=pagetype($file);
326                 if (! defined $type || $type=~/^_/) {
327                         error(sprintf(gettext("%s is not an editable page"), $page));
328                 }
329                 if (! $form->submitted) {
330                         $form->field(name => "rcsinfo",
331                                 value => rcs_prepedit($file), force => 1);
332                 }
333                 $form->field(name => "editcontent", validate => '/.*/');
334         }
335         else {
336                 $type=$form->param('type');
337                 if (defined $type && length $type && $hooks{htmlize}{$type}) {
338                         $type=possibly_foolish_untaint($type);
339                 }
340                 elsif (defined $from && exists $pagesources{$from}) {
341                         # favor the type of linking page
342                         $type=pagetype($pagesources{$from});
343                 }
344                 $type=$config{default_pageext} unless defined $type;
345                 $file=$page.".".$type;
346                 if (! $form->submitted) {
347                         $form->field(name => "rcsinfo", value => "", force => 1);
348                 }
349                 $form->field(name => "editcontent", validate => '/.+/');
350         }
351
352         $form->field(name => "do", type => 'hidden');
353         $form->field(name => "sid", type => "hidden", value => $session->id,
354                 force => 1);
355         $form->field(name => "from", type => 'hidden');
356         $form->field(name => "rcsinfo", type => 'hidden');
357         $form->field(name => "subpage", type => 'hidden');
358         $form->field(name => "page", value => pagetitle($page, 1), force => 1);
359         $form->field(name => "type", value => $type, force => 1);
360         $form->field(name => "comments", type => "text", size => 80);
361         $form->field(name => "editcontent", type => "textarea", rows => 20,
362                 cols => 80);
363         $form->tmpl_param("can_commit", $config{rcs});
364         $form->tmpl_param("indexlink", indexlink());
365         $form->tmpl_param("helponformattinglink",
366                 htmllink($page, $page, "ikiwiki/formatting",
367                         noimageinline => 1,
368                         linktext => "FormattingHelp"));
369         
370         if ($form->submitted eq "Cancel") {
371                 if ($form->field("do") eq "create" && defined $from) {
372                         redirect($q, "$config{url}/".htmlpage($from));
373                 }
374                 elsif ($form->field("do") eq "create") {
375                         redirect($q, $config{url});
376                 }
377                 else {
378                         redirect($q, "$config{url}/".htmlpage($page));
379                 }
380                 return;
381         }
382         elsif ($form->submitted eq "Preview") {
383                 my $new=not exists $pagesources{$page};
384                 if ($new) {
385                         # temporarily record its type
386                         $pagesources{$page}=$page.".".$type;
387                 }
388
389                 my $content=$form->field('editcontent');
390
391                 run_hooks(editcontent => sub {
392                         $content=shift->(
393                                 content => $content,
394                                 page => $page,
395                                 cgi => $q,
396                                 session => $session,
397                         );
398                 });
399                 my $preview=htmlize($page, $page, $type,
400                         linkify($page, $page,
401                         preprocess($page, $page,
402                         filter($page, $page, $content), 0, 1)));
403                 run_hooks(format => sub {
404                         $preview=shift->(
405                                 page => $page,
406                                 content => $preview,
407                         );
408                 });
409                 $form->tmpl_param("page_preview", $preview);
410         
411                 if ($new) {
412                         delete $pagesources{$page};
413                 }
414                 # previewing may have created files on disk
415                 saveindex();
416         }
417         elsif ($form->submitted eq "Save Page") {
418                 $form->tmpl_param("page_preview", "");
419         }
420         $form->tmpl_param("page_conflict", "");
421         
422         if ($form->submitted ne "Save Page" || ! $form->validate) {
423                 if ($form->field("do") eq "create") {
424                         my @page_locs;
425                         my $best_loc;
426                         if (! defined $from || ! length $from ||
427                             $from ne $form->field('from') ||
428                             file_pruned($from, $config{srcdir}) ||
429                             $from=~/^\// ||
430                             $form->submitted eq "Preview") {
431                                 @page_locs=$best_loc=$page;
432                         }
433                         else {
434                                 my $dir=$from."/";
435                                 $dir=~s![^/]+/+$!!;
436                                 
437                                 if ((defined $form->field('subpage') && length $form->field('subpage')) ||
438                                     $page eq gettext('discussion')) {
439                                         $best_loc="$from/$page";
440                                 }
441                                 else {
442                                         $best_loc=$dir.$page;
443                                 }
444                                 
445                                 push @page_locs, $dir.$page;
446                                 push @page_locs, "$from/$page";
447                                 while (length $dir) {
448                                         $dir=~s![^/]+/+$!!;
449                                         push @page_locs, $dir.$page;
450                                 }
451                         
452                                 push @page_locs, "$config{userdir}/$page"
453                                         if length $config{userdir};
454                         }
455
456                         @page_locs = grep {
457                                 ! exists $pagecase{lc $_}
458                         } @page_locs;
459                         if (! @page_locs) {
460                                 # hmm, someone else made the page in the
461                                 # meantime?
462                                 if ($form->submitted eq "Preview") {
463                                         # let them go ahead with the edit
464                                         # and resolve the conflict at save
465                                         # time
466                                         @page_locs=$page;
467                                 }
468                                 else {
469                                         redirect($q, "$config{url}/".htmlpage($page));
470                                         return;
471                                 }
472                         }
473
474                         my @editable_locs = grep {
475                                 check_canedit($_, $q, $session, 1)
476                         } @page_locs;
477                         if (! @editable_locs) {
478                                 # let it throw an error this time
479                                 map { check_canedit($_, $q, $session) } @page_locs;
480                         }
481                         
482                         my @page_types;
483                         if (exists $hooks{htmlize}) {
484                                 @page_types=grep { !/^_/ }
485                                         keys %{$hooks{htmlize}};
486                         }
487                         
488                         $form->tmpl_param("page_select", 1);
489                         $form->field(name => "page", type => 'select',
490                                 options => [ map { pagetitle($_, 1) } @editable_locs ],
491                                 value => pagetitle($best_loc, 1));
492                         $form->field(name => "type", type => 'select',
493                                 options => \@page_types);
494                         $form->title(sprintf(gettext("creating %s"), pagetitle($page)));
495                         
496                 }
497                 elsif ($form->field("do") eq "edit") {
498                         check_canedit($page, $q, $session);
499                         if (! defined $form->field('editcontent') || 
500                             ! length $form->field('editcontent')) {
501                                 my $content="";
502                                 if (exists $pagesources{$page}) {
503                                         $content=readfile(srcfile($pagesources{$page}));
504                                         $content=~s/\n/\r\n/g;
505                                 }
506                                 $form->field(name => "editcontent", value => $content,
507                                         force => 1);
508                         }
509                         $form->tmpl_param("page_select", 0);
510                         $form->field(name => "page", type => 'hidden');
511                         $form->field(name => "type", type => 'hidden');
512                         $form->title(sprintf(gettext("editing %s"), pagetitle($page)));
513                 }
514                 
515                 showform($form, \@buttons, $session, $q, forcebaseurl => $baseurl);
516         }
517         else {
518                 # save page
519                 check_canedit($page, $q, $session);
520         
521                 # The session id is stored on the form and checked to
522                 # guard against CSRF. But only if the user is logged in,
523                 # as anonok can allow anonymous edits.
524                 if (defined $session->param("name")) {
525                         my $sid=$q->param('sid');
526                         if (! defined $sid || $sid ne $session->id) {
527                                 error(gettext("Your login session has expired."));
528                         }
529                 }
530
531                 my $exists=-e "$config{srcdir}/$file";
532
533                 if ($form->field("do") ne "create" && ! $exists &&
534                     ! defined srcfile($file, 1)) {
535                         $form->tmpl_param("page_gone", 1);
536                         $form->field(name => "do", value => "create", force => 1);
537                         $form->tmpl_param("page_select", 0);
538                         $form->field(name => "page", type => 'hidden');
539                         $form->field(name => "type", type => 'hidden');
540                         $form->title(sprintf(gettext("editing %s"), $page));
541                         showform($form, \@buttons, $session, $q, forcebaseurl => $baseurl);
542                         return;
543                 }
544                 elsif ($form->field("do") eq "create" && $exists) {
545                         $form->tmpl_param("creation_conflict", 1);
546                         $form->field(name => "do", value => "edit", force => 1);
547                         $form->tmpl_param("page_select", 0);
548                         $form->field(name => "page", type => 'hidden');
549                         $form->field(name => "type", type => 'hidden');
550                         $form->title(sprintf(gettext("editing %s"), $page));
551                         $form->field("editcontent", 
552                                 value => readfile("$config{srcdir}/$file").
553                                          "\n\n\n".$form->field("editcontent"),
554                                 force => 1);
555                         showform($form, \@buttons, $session, $q, forcebaseurl => $baseurl);
556                         return;
557                 }
558                 
559                 my $content=$form->field('editcontent');
560                 run_hooks(editcontent => sub {
561                         $content=shift->(
562                                 content => $content,
563                                 page => $page,
564                                 cgi => $q,
565                                 session => $session,
566                         );
567                 });
568                 $content=~s/\r\n/\n/g;
569                 $content=~s/\r/\n/g;
570                 $content.="\n" if $content !~ /\n$/;
571
572                 $config{cgi}=0; # avoid cgi error message
573                 eval { writefile($file, $config{srcdir}, $content) };
574                 $config{cgi}=1;
575                 if ($@) {
576                         $form->field(name => "rcsinfo", value => rcs_prepedit($file),
577                                 force => 1);
578                         $form->tmpl_param("failed_save", 1);
579                         $form->tmpl_param("error_message", $@);
580                         $form->field("editcontent", value => $content, force => 1);
581                         $form->tmpl_param("page_select", 0);
582                         $form->field(name => "page", type => 'hidden');
583                         $form->field(name => "type", type => 'hidden');
584                         $form->title(sprintf(gettext("editing %s"), $page));
585                         showform($form, \@buttons, $session, $q,
586                                 forcebaseurl => $baseurl);
587                         return;
588                 }
589                 
590                 my $conflict;
591                 if ($config{rcs}) {
592                         my $message="";
593                         if (defined $form->field('comments') &&
594                             length $form->field('comments')) {
595                                 $message=$form->field('comments');
596                         }
597                         
598                         if (! $exists) {
599                                 rcs_add($file);
600                         }
601
602                         # Prevent deadlock with post-commit hook by
603                         # signaling to it that it should not try to
604                         # do anything.
605                         disable_commit_hook();
606                         $conflict=rcs_commit($file, $message,
607                                 $form->field("rcsinfo"),
608                                 $session->param("name"), $ENV{REMOTE_ADDR});
609                         enable_commit_hook();
610                         rcs_update();
611                 }
612                 
613                 # Refresh even if there was a conflict, since other changes
614                 # may have been committed while the post-commit hook was
615                 # disabled.
616                 require IkiWiki::Render;
617                 refresh();
618                 saveindex();
619
620                 if (defined $conflict) {
621                         $form->field(name => "rcsinfo", value => rcs_prepedit($file),
622                                 force => 1);
623                         $form->tmpl_param("page_conflict", 1);
624                         $form->field("editcontent", value => $conflict, force => 1);
625                         $form->field("do", "edit", force => 1);
626                         $form->tmpl_param("page_select", 0);
627                         $form->field(name => "page", type => 'hidden');
628                         $form->field(name => "type", type => 'hidden');
629                         $form->title(sprintf(gettext("editing %s"), $page));
630                         showform($form, \@buttons, $session, $q,
631                                 forcebaseurl => $baseurl);
632                         return;
633                 }
634                 else {
635                         # The trailing question mark tries to avoid broken
636                         # caches and get the most recent version of the page.
637                         redirect($q, "$config{url}/".htmlpage($page)."?updated");
638                 }
639         }
640 } #}}}
641
642 sub cgi_getsession ($) { #{{{
643         my $q=shift;
644
645         eval q{use CGI::Session};
646         error($@) if $@;
647         CGI::Session->name("ikiwiki_session_".encode_utf8($config{wikiname}));
648         
649         my $oldmask=umask(077);
650         my $session = CGI::Session->new("driver:DB_File", $q,
651                 { FileName => "$config{wikistatedir}/sessions.db" });
652         umask($oldmask);
653
654         return $session;
655 } #}}}
656
657 sub cgi_savesession ($) { #{{{
658         my $session=shift;
659
660         # Force session flush with safe umask.
661         my $oldmask=umask(077);
662         $session->flush;
663         umask($oldmask);
664 } #}}}
665
666 sub cgi (;$$) { #{{{
667         my $q=shift;
668         my $session=shift;
669
670         if (! $q) {
671                 eval q{use CGI};
672                 error($@) if $@;
673         
674                 binmode(STDIN);
675                 $q=CGI->new;
676                 binmode(STDIN, ":utf8");
677         
678                 run_hooks(cgi => sub { shift->($q) });
679         }
680
681         my $do=$q->param('do');
682         if (! defined $do || ! length $do) {
683                 my $error = $q->cgi_error;
684                 if ($error) {
685                         error("Request not processed: $error");
686                 }
687                 else {
688                         error("\"do\" parameter missing");
689                 }
690         }
691         
692         # Need to lock the wiki before getting a session.
693         lockwiki();
694         loadindex();
695         
696         if (! $session) {
697                 $session=cgi_getsession($q);
698         }
699         
700         # Auth hooks can sign a user in.
701         if ($do ne 'signin' && ! defined $session->param("name")) {
702                 run_hooks(auth => sub {
703                         shift->($q, $session)
704                 });
705                 if (defined $session->param("name")) {
706                         # Make sure whatever user was authed is in the
707                         # userinfo db.
708                         if (! userinfo_get($session->param("name"), "regdate")) {
709                                 userinfo_setall($session->param("name"), {
710                                         email => "",
711                                         password => "",
712                                         regdate => time,
713                                 }) || error("failed adding user");
714                         }
715                 }
716         }
717         
718         if (defined $session->param("name") &&
719             userinfo_get($session->param("name"), "banned")) {
720                 print $q->header(-status => "403 Forbidden");
721                 $session->delete();
722                 print gettext("You are banned.");
723                 cgi_savesession($session);
724         }
725
726         run_hooks(sessioncgi => sub { shift->($q, $session) });
727
728         if ($do eq 'signin') {
729                 cgi_signin($q, $session);
730                 cgi_savesession($session);
731         }
732         elsif ($do eq 'prefs') {
733                 cgi_prefs($q, $session);
734         }
735         elsif ($do eq 'create' || $do eq 'edit') {
736                 cgi_editpage($q, $session);
737         }
738         elsif (defined $session->param("postsignin") || $do eq 'postsignin') {
739                 cgi_postsignin($q, $session);
740         }
741         else {
742                 error("unknown do parameter");
743         }
744 } #}}}
745
746 1