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