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