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