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