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