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