web commit by http://getopenid.com/ptecza: Response
[ikiwiki] / 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                         #translators: The first parameter is a page name,
50                         #translators: second is the user who locked it.
51                         error(sprintf(gettext("%s is locked by %s and cannot be edited"),
52                                 htmllink("", "", $page, 1),
53                                 userlink($admin)));
54                 }
55         }
56
57         return 0;
58 } #}}}
59
60 sub decode_form_utf8 ($) { #{{{
61         my $form = shift;
62         foreach my $f ($form->field) {
63                 next if Encode::is_utf8(scalar $form->field($f));
64                 $form->field(name  => $f,
65                              value => decode_utf8($form->field($f)),
66                              force => 1,
67                             );
68         }
69 } #}}}
70
71 sub cgi_recentchanges ($) { #{{{
72         my $q=shift;
73         
74         # Optimisation: building recentchanges means calculating lots of
75         # links. Memoizing htmllink speeds it up a lot (can't be memoized
76         # during page builds as the return values may change, but they
77         # won't here.)
78         eval q{use Memoize};
79         error($@) if $@;
80         memoize("htmllink");
81
82         eval q{use Time::Duration};
83         error($@) if $@;
84
85         my $changelog=[rcs_recentchanges(100)];
86         foreach my $change (@$changelog) {
87                 $change->{when} = concise(ago($change->{when}));
88
89                 $change->{user} = userlink($change->{user});
90
91                 my $is_excess = exists $change->{pages}[10]; # limit pages to first 10
92                 delete @{$change->{pages}}[10 .. @{$change->{pages}}] if $is_excess;
93                 $change->{pages} = [
94                         map {
95                                 $_->{link} = htmllink("", "", $_->{page}, 1, 0, pagetitle($_->{page}));
96                                 $_;
97                         } @{$change->{pages}}
98                 ];
99                 push @{$change->{pages}}, { link => '...' } if $is_excess;
100         }
101
102         my $template=template("recentchanges.tmpl"); 
103         $template->param(
104                 title => "RecentChanges",
105                 indexlink => indexlink(),
106                 wikiname => $config{wikiname},
107                 changelog => $changelog,
108                 baseurl => baseurl(),
109         );
110         run_hooks(pagetemplate => sub {
111                 shift->(page => "", destpage => "", template => $template);
112         });
113         print $q->header(-charset => 'utf-8'), $template->output;
114 } #}}}
115
116 sub cgi_signin ($$) { #{{{
117         my $q=shift;
118         my $session=shift;
119
120         eval q{use CGI::FormBuilder};
121         error($@) if $@;
122         my $form = CGI::FormBuilder->new(
123                 title => "signin",
124                 header => 1,
125                 charset => "utf-8",
126                 method => 'POST',
127                 required => 'NONE',
128                 javascript => 0,
129                 params => $q,
130                 action => $config{cgiurl},
131                 header => 0,
132                 template => scalar template_params("signin.tmpl"),
133                 stylesheet => baseurl()."style.css",
134         );
135         my $buttons=["Login"];
136         
137         $form->field(name => "do", type => "hidden");
138         
139         if ($q->param("do") ne "signin" && !$form->submitted) {
140                 $form->text(gettext("You need to log in first."));
141         }
142         
143         run_hooks(formbuilder_setup => sub {
144                 shift->(form => $form, cgi => $q, session => $session);
145         });
146         
147         decode_form_utf8($form);
148
149         if (exists $hooks{formbuilder}) {
150                 run_hooks(formbuilder => sub {
151                         shift->(form => $form, cgi => $q, session => $session,
152                                 buttons => $buttons);
153                 });
154         }
155         else {
156                 if ($form->submitted) {
157                         $form->validate;
158                 }
159                 printheader($session);
160                 print misctemplate($form->title, $form->render(submit => $buttons));
161         }
162 } #}}}
163
164 sub cgi_postsignin ($$) { #{{{
165         my $q=shift;
166         my $session=shift;
167
168         # Continue with whatever was being done before the signin process.
169         if (defined $q->param("do") && $q->param("do") ne "signin" &&
170             defined $session->param("postsignin")) {
171                 my $postsignin=CGI->new($session->param("postsignin"));
172                 $session->clear("postsignin");
173                 cgi($postsignin, $session);
174                 cgi_savesession($session);
175                 exit;
176         }
177         else {
178                 redirect($q, $config{url});
179         }
180 } #}}}
181
182 sub cgi_prefs ($$) { #{{{
183         my $q=shift;
184         my $session=shift;
185
186         eval q{use CGI::FormBuilder};
187         error($@) if $@;
188         my $form = CGI::FormBuilder->new(
189                 title => "preferences",
190                 header => 0,
191                 charset => "utf-8",
192                 method => 'POST',
193                 validate => {
194                         email => 'EMAIL',
195                 },
196                 required => 'NONE',
197                 javascript => 0,
198                 params => $q,
199                 action => $config{cgiurl},
200                 template => scalar 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 => scalar template_params("editpage.tmpl"),
295         );
296         
297         run_hooks(formbuilder_setup => sub {
298                 shift->(form => $form, cgi => $q, session => $session);
299         });
300         
301         decode_form_utf8($form);
302         
303         # This untaint is safe because titlepage removes any problematic
304         # characters.
305         my ($page)=$form->field('page');
306         $page=titlepage(possibly_foolish_untaint($page));
307         if (! defined $page || ! length $page || file_pruned($page, $config{srcdir}) || $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                             file_pruned($from, $config{srcdir}) ||
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 gettext('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                         push @page_locs, "$config{userdir}/$page"
422                                 if length $config{userdir};
423
424                         @page_locs = grep {
425                                 ! exists $pagecase{lc $_} &&
426                                 ! page_locked($_, $session, 1)
427                         } @page_locs;
428                         
429                         if (! @page_locs) {
430                                 # hmm, someone else made the page in the
431                                 # meantime?
432                                 redirect($q, "$config{url}/".htmlpage($page));
433                                 return;
434                         }
435                         
436                         my @page_types;
437                         if (exists $hooks{htmlize}) {
438                                 @page_types=keys %{$hooks{htmlize}};
439                         }
440                         
441                         $form->tmpl_param("page_select", 1);
442                         $form->field(name => "page", type => 'select',
443                                 options => \@page_locs, value => $best_loc);
444                         $form->field(name => "type", type => 'select',
445                                 options => \@page_types);
446                         $form->title(sprintf(gettext("creating %s"), pagetitle($page)));
447                 }
448                 elsif ($form->field("do") eq "edit") {
449                         page_locked($page, $session);
450                         if (! defined $form->field('editcontent') || 
451                             ! length $form->field('editcontent')) {
452                                 my $content="";
453                                 if (exists $pagesources{$page}) {
454                                         $content=readfile(srcfile($pagesources{$page}));
455                                         $content=~s/\n/\r\n/g;
456                                 }
457                                 $form->field(name => "editcontent", value => $content,
458                                         force => 1);
459                         }
460                         $form->tmpl_param("page_select", 0);
461                         $form->field(name => "page", type => 'hidden');
462                         $form->field(name => "type", type => 'hidden');
463                         $form->title(sprintf(gettext("editing %s"), pagetitle($page)));
464                 }
465                 
466                 print $form->render(submit => \@buttons);
467         }
468         else {
469                 # save page
470                 page_locked($page, $session);
471                 
472                 my $content=$form->field('editcontent');
473
474                 $content=~s/\r\n/\n/g;
475                 $content=~s/\r/\n/g;
476                 writefile($file, $config{srcdir}, $content);
477                 
478                 if ($config{rcs}) {
479                         my $message="";
480                         if (defined $form->field('comments') &&
481                             length $form->field('comments')) {
482                                 $message=$form->field('comments');
483                         }
484                         
485                         if ($newfile) {
486                                 rcs_add($file);
487                         }
488                         # prevent deadlock with post-commit hook
489                         unlockwiki();
490                         # presumably the commit will trigger an update
491                         # of the wiki
492                         my $conflict=rcs_commit($file, $message,
493                                 $form->field("rcsinfo"),
494                                 $session->param("name"), $ENV{REMOTE_ADDR});
495                 
496                         if (defined $conflict) {
497                                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
498                                         force => 1);
499                                 $form->tmpl_param("page_conflict", 1);
500                                 $form->field("editcontent", value => $conflict, force => 1);
501                                 $form->field(name => "comments", value => $form->field('comments'), force => 1);
502                                 $form->field("do", "edit)");
503                                 $form->tmpl_param("page_select", 0);
504                                 $form->field(name => "page", type => 'hidden');
505                                 $form->field(name => "type", type => 'hidden');
506                                 $form->title(sprintf(gettext("editing %s"), $page));
507                                 print $form->render(submit => \@buttons);
508                                 return;
509                         }
510                 }
511                 else {
512                         require IkiWiki::Render;
513                         refresh();
514                         saveindex();
515                 }
516                 
517                 # The trailing question mark tries to avoid broken
518                 # caches and get the most recent version of the page.
519                 redirect($q, "$config{url}/".htmlpage($page)."?updated");
520         }
521 } #}}}
522
523 sub cgi_getsession ($) { #{{{
524         my $q=shift;
525
526         eval q{use CGI::Session};
527         CGI::Session->name("ikiwiki_session_".encode_utf8($config{wikiname}));
528         
529         my $oldmask=umask(077);
530         my $session = CGI::Session->new("driver:DB_File", $q,
531                 { FileName => "$config{wikistatedir}/sessions.db" });
532         umask($oldmask);
533
534         return $session;
535 } #}}}
536
537 sub cgi_savesession ($) { #{{{
538         my $session=shift;
539
540         # Force session flush with safe umask.
541         my $oldmask=umask(077);
542         $session->flush;
543         umask($oldmask);
544 }
545
546 sub cgi (;$$) { #{{{
547         my $q=shift;
548         my $session=shift;
549
550         if (! $q) {
551                 eval q{use CGI};
552                 error($@) if $@;
553         
554                 $q=CGI->new;
555         
556                 run_hooks(cgi => sub { shift->($q) });
557         }
558
559         my $do=$q->param('do');
560         if (! defined $do || ! length $do) {
561                 my $error = $q->cgi_error;
562                 if ($error) {
563                         error("Request not processed: $error");
564                 }
565                 else {
566                         error("\"do\" parameter missing");
567                 }
568         }
569         
570         # Things that do not need a session.
571         if ($do eq 'recentchanges') {
572                 cgi_recentchanges($q);
573                 return;
574         }
575         elsif ($do eq 'hyperestraier') {
576                 cgi_hyperestraier();
577         }
578
579         # Need to lock the wiki before getting a session.
580         lockwiki();
581         
582         if (! $session) {
583                 $session=cgi_getsession($q);
584         }
585         
586         # Auth hooks can sign a user in.
587         if ($do ne 'signin' && ! defined $session->param("name")) {
588                 run_hooks(auth => sub {
589                         shift->($q, $session)
590                 });
591                 if (defined $session->param("name")) {
592                         # Make sure whatever user was authed is in the
593                         # userinfo db.
594                         if (! userinfo_get($session->param("name"), "regdate")) {
595                                 userinfo_setall($session->param("name"), {
596                                         email => "",
597                                         password => "",
598                                         regdate => time,
599                                 });
600                         }
601                 }
602         }
603
604         # Everything below this point needs the user to be signed in.
605         if (((! $config{anonok} || $do eq 'prefs') &&
606              (! defined $session->param("name") ||
607              ! userinfo_get($session->param("name"), "regdate")))
608             || $do eq 'signin') {
609                 if ($do ne 'signin' && ! defined $session->param("postsignin")) {
610                         $session->param(postsignin => $ENV{QUERY_STRING});
611                 }
612                 cgi_signin($q, $session);
613                 cgi_savesession($session);
614                 return;
615         }
616         elsif (defined $session->param("postsignin")) {
617                 cgi_postsignin($q, $session);
618         }
619
620         if (defined $session->param("name") && userinfo_get($session->param("name"), "banned")) {
621                 print $q->header(-status => "403 Forbidden");
622                 $session->delete();
623                 print gettext("You are banned.");
624                 cgi_savesession($session);
625                 exit;
626         }
627         
628         if ($do eq 'create' || $do eq 'edit') {
629                 cgi_editpage($q, $session);
630         }
631         elsif ($do eq 'prefs') {
632                 cgi_prefs($q, $session);
633         }
634         elsif ($do eq 'blog') {
635                 my $page=titlepage(decode_utf8($q->param('title')));
636                 $page=~s/(\/)/"__".ord($1)."__"/eg; # escape slashes too
637                 # if the page already exists, munge it to be unique
638                 my $from=$q->param('from');
639                 my $add="";
640                 while (exists $pagecase{lc "$from/$page$add"}) {
641                         $add=1 unless length $add;
642                         $add++;
643                 }
644                 $q->param('page', $page.$add);
645                 # now run same as create
646                 $q->param('do', 'create');
647                 cgi_editpage($q, $session);
648         }
649         elsif ($do eq 'postsignin') {
650                 error(gettext("login failed, perhaps you need to turn on cookies?"));
651         }
652         else {
653                 error("unknown do parameter");
654         }
655 } #}}}
656
657 sub userlink ($) { #{{{
658         my $user=shift;
659
660         eval q{use CGI 'escapeHTML'};
661         error($@) if $@;
662         if ($user =~ m!^https?://! &&
663             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
664                 # Munge user-urls, as used by eg, OpenID.
665                 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
666                 my $display=$oid->display;
667                 # Convert "user.somehost.com" to "user [somehost.com]".
668                 if ($display !~ /\[/) {
669                         $display=~s/^(.*?)\.([^.]+\.[a-z]+)$/$1 [$2]/;
670                 }
671                 # Convert "http://somehost.com/user" to "user [somehost.com]".
672                 if ($display !~ /\[/) {
673                         $display=~s/^https?:\/\/(.+)\/([^\/]+)$/$2 [$1]/;
674                 }
675                 $display=~s!^https?://!!; # make sure this is removed
676                 return "<a href=\"$user\">".escapeHTML($display)."</a>";
677         }
678         else {
679                 return htmllink("", "", escapeHTML(
680                         length $config{userdir} ? $config{userdir}."/".$user : $user
681                 ), 1);
682         }
683 } #}}}
684
685 1