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