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