]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/CGI.pm
Corrected a fuzzy. Changed some error message translation to use ": %s"
[git.ikiwiki.info.git] / IkiWiki / CGI.pm
1 #!/usr/bin/perl
3 use warnings;
4 use strict;
5 use IkiWiki;
6 use IkiWiki::UserInfo;
7 use open qw{:utf8 :std};
8 use Encode;
10 package IkiWiki;
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         }
22 } #}}}
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 } #}}}
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);
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;
49                         error(sprintf(gettext("%s is locked by %s and cannot be edited"),
50                                 htmllink("", "", $page, 1),
51                                 userlink($admin)));
52                 }
53         }
55         return 0;
56 } #}}}
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 } #}}}
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");
80         eval q{use Time::Duration};
81         error($@) if $@;
83         my $changelog=[rcs_recentchanges(100)];
84         foreach my $change (@$changelog) {
85                 $change->{when} = concise(ago($change->{when}));
87                 $change->{user} = userlink($change->{user});
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         }
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 } #}}}
114 sub cgi_signin ($$) { #{{{
115         my $q=shift;
116         my $session=shift;
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);
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 } #}}}
163 sub cgi_postsignin ($$) { #{{{
164         my $q=shift;
165         my $session=shift;
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 } #}}}
181 sub cgi_prefs ($$) { #{{{
182         my $q=shift;
183         my $session=shift;
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"];
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         }
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 } #}}}
272 sub cgi_editpage ($$) { #{{{
273         my $q=shift;
274         my $session=shift;
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         }
336         my $newfile=0;
337         if (! -e "$config{srcdir}/$file") {
338                 $newfile=1;
339         }
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                         push @page_locs, "$config{userdir}/$page"
423                                 if length $config{userdir};
425                         @page_locs = grep {
426                                 ! exists $pagecase{lc $_} &&
427                                 ! page_locked($_, $session, 1)
428                         } @page_locs;
429                         
430                         if (! @page_locs) {
431                                 # hmm, someone else made the page in the
432                                 # meantime?
433                                 redirect($q, "$config{url}/".htmlpage($page));
434                                 return;
435                         }
436                         
437                         my @page_types;
438                         if (exists $hooks{htmlize}) {
439                                 @page_types=keys %{$hooks{htmlize}};
440                         }
441                         
442                         $form->tmpl_param("page_select", 1);
443                         $form->field(name => "page", type => 'select',
444                                 options => \@page_locs, value => $best_loc);
445                         $form->field(name => "type", type => 'select',
446                                 options => \@page_types);
447                         $form->title(sprintf(gettext("creating %s"), pagetitle($page)));
448                 }
449                 elsif ($form->field("do") eq "edit") {
450                         page_locked($page, $session);
451                         if (! defined $form->field('editcontent') || 
452                             ! length $form->field('editcontent')) {
453                                 my $content="";
454                                 if (exists $pagesources{$page}) {
455                                         $content=readfile(srcfile($pagesources{$page}));
456                                         $content=~s/\n/\r\n/g;
457                                 }
458                                 $form->field(name => "editcontent", value => $content,
459                                         force => 1);
460                         }
461                         $form->tmpl_param("page_select", 0);
462                         $form->field(name => "page", type => 'hidden');
463                         $form->field(name => "type", type => 'hidden');
464                         $form->title(sprintf(gettext("editing %s"), pagetitle($page)));
465                 }
466                 
467                 print $form->render(submit => \@buttons);
468         }
469         else {
470                 # save page
471                 page_locked($page, $session);
472                 
473                 my $content=$form->field('editcontent');
475                 $content=~s/\r\n/\n/g;
476                 $content=~s/\r/\n/g;
477                 writefile($file, $config{srcdir}, $content);
478                 
479                 if ($config{rcs}) {
480                         my $message="";
481                         if (defined $form->field('comments') &&
482                             length $form->field('comments')) {
483                                 $message=$form->field('comments');
484                         }
485                         
486                         if ($newfile) {
487                                 rcs_add($file);
488                         }
489                         # prevent deadlock with post-commit hook
490                         unlockwiki();
491                         # presumably the commit will trigger an update
492                         # of the wiki
493                         my $conflict=rcs_commit($file, $message,
494                                 $form->field("rcsinfo"),
495                                 $session->param("name"), $ENV{REMOTE_ADDR});
496                 
497                         if (defined $conflict) {
498                                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
499                                         force => 1);
500                                 $form->tmpl_param("page_conflict", 1);
501                                 $form->field("editcontent", value => $conflict, force => 1);
502                                 $form->field(name => "comments", value => $form->field('comments'), force => 1);
503                                 $form->field("do", "edit)");
504                                 $form->tmpl_param("page_select", 0);
505                                 $form->field(name => "page", type => 'hidden');
506                                 $form->field(name => "type", type => 'hidden');
507                                 $form->title(sprintf(gettext("editing %s"), $page));
508                                 print $form->render(submit => \@buttons);
509                                 return;
510                         }
511                 }
512                 else {
513                         require IkiWiki::Render;
514                         refresh();
515                         saveindex();
516                 }
517                 
518                 # The trailing question mark tries to avoid broken
519                 # caches and get the most recent version of the page.
520                 redirect($q, "$config{url}/".htmlpage($page)."?updated");
521         }
522 } #}}}
524 sub cgi_getsession ($) { #{{{
525         my $q=shift;
527         eval q{use CGI::Session};
528         CGI::Session->name("ikiwiki_session_".encode_utf8($config{wikiname}));
529         
530         my $oldmask=umask(077);
531         my $session = CGI::Session->new("driver:DB_File", $q,
532                 { FileName => "$config{wikistatedir}/sessions.db" });
533         umask($oldmask);
535         return $session;
536 } #}}}
538 sub cgi_savesession ($) { #{{{
539         my $session=shift;
541         # Force session flush with safe umask.
542         my $oldmask=umask(077);
543         $session->flush;
544         umask($oldmask);
547 sub cgi (;$$) { #{{{
548         my $q=shift;
549         my $session=shift;
551         if (! $q) {
552                 eval q{use CGI};
553                 error($@) if $@;
554         
555                 $q=CGI->new;
556         
557                 run_hooks(cgi => sub { shift->($q) });
558         }
560         my $do=$q->param('do');
561         if (! defined $do || ! length $do) {
562                 my $error = $q->cgi_error;
563                 if ($error) {
564                         error("Request not processed: $error");
565                 }
566                 else {
567                         error("\"do\" parameter missing");
568                 }
569         }
570         
571         # Things that do not need a session.
572         if ($do eq 'recentchanges') {
573                 cgi_recentchanges($q);
574                 return;
575         }
576         elsif ($do eq 'hyperestraier') {
577                 cgi_hyperestraier();
578         }
580         # Need to lock the wiki before getting a session.
581         lockwiki();
582         
583         if (! $session) {
584                 $session=cgi_getsession($q);
585         }
586         
587         # Auth hooks can sign a user in.
588         if ($do ne 'signin' && ! defined $session->param("name")) {
589                 run_hooks(auth => sub {
590                         shift->($q, $session)
591                 });
592                 if (defined $session->param("name")) {
593                         # Make sure whatever user was authed is in the
594                         # userinfo db.
595                         if (! userinfo_get($session->param("name"), "regdate")) {
596                                 userinfo_setall($session->param("name"), {
597                                         email => "",
598                                         password => "",
599                                         regdate => time,
600                                 });
601                         }
602                 }
603         }
605         # Everything below this point needs the user to be signed in.
606         if (((! $config{anonok} || $do eq 'prefs') &&
607              (! defined $session->param("name") ||
608              ! userinfo_get($session->param("name"), "regdate")))
609             || $do eq 'signin') {
610                 if ($do ne 'signin' && ! defined $session->param("postsignin")) {
611                         $session->param(postsignin => $ENV{QUERY_STRING});
612                 }
613                 cgi_signin($q, $session);
614                 cgi_savesession($session);
615                 return;
616         }
617         elsif (defined $session->param("postsignin")) {
618                 cgi_postsignin($q, $session);
619         }
621         if (defined $session->param("name") && userinfo_get($session->param("name"), "banned")) {
622                 print $q->header(-status => "403 Forbidden");
623                 $session->delete();
624                 print gettext("You are banned.");
625                 cgi_savesession($session);
626                 exit;
627         }
628         
629         if ($do eq 'create' || $do eq 'edit') {
630                 cgi_editpage($q, $session);
631         }
632         elsif ($do eq 'prefs') {
633                 cgi_prefs($q, $session);
634         }
635         elsif ($do eq 'blog') {
636                 my $page=titlepage(decode_utf8($q->param('title')));
637                 $page=~s/(\/)/"__".ord($1)."__"/eg; # escape slashes too
638                 # if the page already exists, munge it to be unique
639                 my $from=$q->param('from');
640                 my $add="";
641                 while (exists $pagecase{lc "$from/$page$add"}) {
642                         $add=1 unless length $add;
643                         $add++;
644                 }
645                 $q->param('page', $page.$add);
646                 # now run same as create
647                 $q->param('do', 'create');
648                 cgi_editpage($q, $session);
649         }
650         else {
651                 error("unknown do parameter");
652         }
653 } #}}}
655 sub userlink ($) { #{{{
656         my $user=shift;
658         eval q{use CGI 'escapeHTML'};
659         error($@) if $@;
660         if ($user =~ m!^https?://! &&
661             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
662                 # Munge user-urls, as used by eg, OpenID.
663                 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
664                 my $display=$oid->display;
665                 # Convert "user.somehost.com" to "user [somehost.com]".
666                 if ($display !~ /\[/) {
667                         $display=~s/^(.*?)\.([^.]+\.[a-z]+)$/$1 [$2]/;
668                 }
669                 # Convert "http://somehost.com/user" to "user [somehost.com]".
670                 if ($display !~ /\[/) {
671                         $display=~s/^https?:\/\/(.+)\/([^\/]+)$/$2 [$1]/;
672                 }
673                 $display=~s!^https?://!!; # make sure this is removed
674                 return "<a href=\"$user\">".escapeHTML($display)."</a>";
675         }
676         else {
677                 return htmllink("", "", escapeHTML(
678                         length $config{userdir} ? $config{userdir}."/".$user : $user
679                 ), 1);
680         }
681 } #}}}