]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/CGI.pm
releasing version 2.31.1
[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 showform ($$$$) { #{{{
25         my $form=shift;
26         my $buttons=shift;
27         my $session=shift;
28         my $cgi=shift;
30         if (exists $hooks{formbuilder}) {
31                 run_hooks(formbuilder => sub {
32                         shift->(form => $form, cgi => $cgi, session => $session,
33                                 buttons => $buttons);
34                 });
35         }
37         printheader($session);
38         print misctemplate($form->title, $form->render(submit => $buttons));
39 }
41 sub redirect ($$) { #{{{
42         my $q=shift;
43         my $url=shift;
44         if (! $config{w3mmode}) {
45                 print $q->redirect($url);
46         }
47         else {
48                 print "Content-type: text/plain\n";
49                 print "W3m-control: GOTO $url\n\n";
50         }
51 } #}}}
53 sub check_canedit ($$$;$) { #{{{
54         my $page=shift;
55         my $q=shift;
56         my $session=shift;
57         my $nonfatal=shift;
58         
59         my $canedit;
60         run_hooks(canedit => sub {
61                 return if defined $canedit;
62                 my $ret=shift->($page, $q, $session);
63                 if (defined $ret) {
64                         if ($ret eq "") {
65                                 $canedit=1;
66                         }
67                         elsif (ref $ret eq 'CODE') {
68                                 $ret->() unless $nonfatal;
69                                 $canedit=0;
70                         }
71                         elsif (defined $ret) {
72                                 error($ret) unless $nonfatal;
73                                 $canedit=0;
74                         }
75                 }
76         });
77         return $canedit;
78 } #}}}
80 sub decode_cgi_utf8 ($) { #{{{
81         my $cgi = shift;
82         foreach my $f ($cgi->param) {
83                 $cgi->param($f, map { decode_utf8 $_ } $cgi->param($f));
84         }
85 } #}}}
87 # Check if the user is signed in. If not, redirect to the signin form and
88 # save their place to return to later.
89 sub needsignin ($$) { #{{{
90         my $q=shift;
91         my $session=shift;
93         if (! defined $session->param("name") ||
94             ! userinfo_get($session->param("name"), "regdate")) {
95                 $session->param(postsignin => $ENV{QUERY_STRING});
96                 cgi_signin($q, $session);
97                 cgi_savesession($session);
98                 exit;
99         }
100 } #}}}  
102 sub cgi_signin ($$) { #{{{
103         my $q=shift;
104         my $session=shift;
106         decode_cgi_utf8($q);
107         eval q{use CGI::FormBuilder};
108         error($@) if $@;
109         my $form = CGI::FormBuilder->new(
110                 title => "signin",
111                 name => "signin",
112                 charset => "utf-8",
113                 method => 'POST',
114                 required => 'NONE',
115                 javascript => 0,
116                 params => $q,
117                 action => $config{cgiurl},
118                 header => 0,
119                 template => {type => 'div'},
120                 stylesheet => baseurl()."style.css",
121         );
122         my $buttons=["Login"];
123         
124         if ($q->param("do") ne "signin" && !$form->submitted) {
125                 $form->text(gettext("You need to log in first."));
126         }
127         $form->field(name => "do", type => "hidden", value => "signin",
128                 force => 1);
129         
130         run_hooks(formbuilder_setup => sub {
131                 shift->(form => $form, cgi => $q, session => $session,
132                         buttons => $buttons);
133         });
135         if ($form->submitted) {
136                 $form->validate;
137         }
139         showform($form, $buttons, $session, $q);
140 } #}}}
142 sub cgi_postsignin ($$) { #{{{
143         my $q=shift;
144         my $session=shift;
145         
146         # Continue with whatever was being done before the signin process.
147         if (defined $session->param("postsignin")) {
148                 my $postsignin=CGI->new($session->param("postsignin"));
149                 $session->clear("postsignin");
150                 cgi($postsignin, $session);
151                 cgi_savesession($session);
152                 exit;
153         }
154         else {
155                 error(gettext("login failed, perhaps you need to turn on cookies?"));
156         }
157 } #}}}
159 sub cgi_prefs ($$) { #{{{
160         my $q=shift;
161         my $session=shift;
163         needsignin($q, $session);
165         decode_cgi_utf8($q);
166         eval q{use CGI::FormBuilder};
167         error($@) if $@;
168         my $form = CGI::FormBuilder->new(
169                 title => "preferences",
170                 name => "preferences",
171                 header => 0,
172                 charset => "utf-8",
173                 method => 'POST',
174                 validate => {
175                         email => 'EMAIL',
176                 },
177                 required => 'NONE',
178                 javascript => 0,
179                 params => $q,
180                 action => $config{cgiurl},
181                 template => {type => 'div'},
182                 stylesheet => baseurl()."style.css",
183                 fieldsets => [
184                         [login => gettext("Login")],
185                         [preferences => gettext("Preferences")],
186                         [admin => gettext("Admin")]
187                 ],
188         );
189         my $buttons=["Save Preferences", "Logout", "Cancel"];
191         run_hooks(formbuilder_setup => sub {
192                 shift->(form => $form, cgi => $q, session => $session,
193                         buttons => $buttons);
194         });
195         
196         $form->field(name => "do", type => "hidden");
197         $form->field(name => "email", size => 50, fieldset => "preferences");
198         $form->field(name => "banned_users", size => 50,
199                 fieldset => "admin");
200         
201         my $user_name=$session->param("name");
202         if (! is_admin($user_name)) {
203                 $form->field(name => "banned_users", type => "hidden");
204         }
206         if (! $form->submitted) {
207                 $form->field(name => "email", force => 1,
208                         value => userinfo_get($user_name, "email"));
209                 if (is_admin($user_name)) {
210                         $form->field(name => "banned_users", force => 1,
211                                 value => join(" ", get_banned_users()));
212                 }
213         }
214         
215         if ($form->submitted eq 'Logout') {
216                 $session->delete();
217                 redirect($q, $config{url});
218                 return;
219         }
220         elsif ($form->submitted eq 'Cancel') {
221                 redirect($q, $config{url});
222                 return;
223         }
224         elsif ($form->submitted eq 'Save Preferences' && $form->validate) {
225                 if (defined $form->field('email')) {
226                         userinfo_set($user_name, 'email', $form->field('email')) ||
227                                 error("failed to set email");
228                 }
229                 if (is_admin($user_name)) {
230                         set_banned_users(grep { ! is_admin($_) }
231                                         split(' ',
232                                                 $form->field("banned_users"))) ||
233                                 error("failed saving changes");
234                 }
235                 $form->text(gettext("Preferences saved."));
236         }
237         
238         showform($form, $buttons, $session, $q);
239 } #}}}
241 sub cgi_editpage ($$) { #{{{
242         my $q=shift;
243         my $session=shift;
245         my @fields=qw(do rcsinfo subpage from page type editcontent comments);
246         my @buttons=("Save Page", "Preview", "Cancel");
247         
248         decode_cgi_utf8($q);
249         eval q{use CGI::FormBuilder};
250         error($@) if $@;
251         my $form = CGI::FormBuilder->new(
252                 title => "editpage",
253                 fields => \@fields,
254                 charset => "utf-8",
255                 method => 'POST',
256                 required => [qw{editcontent}],
257                 javascript => 0,
258                 params => $q,
259                 action => $config{cgiurl},
260                 header => 0,
261                 table => 0,
262                 template => scalar template_params("editpage.tmpl"),
263                 wikiname => $config{wikiname},
264         );
265         
266         run_hooks(formbuilder_setup => sub {
267                 shift->(form => $form, cgi => $q, session => $session,
268                         buttons => \@buttons);
269         });
270         
271         # This untaint is safe because titlepage removes any problematic
272         # characters.
273         my ($page)=$form->field('page');
274         $page=titlepage(possibly_foolish_untaint($page));
275         if (! defined $page || ! length $page ||
276             file_pruned($page, $config{srcdir}) || $page=~/^\//) {
277                 error("bad page name");
278         }
279         
280         my $from;
281         if (defined $form->field('from')) {
282                 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
283         }
284         
285         my $file;
286         my $type;
287         if (exists $pagesources{$page} && $form->field("do") ne "create") {
288                 $file=$pagesources{$page};
289                 $type=pagetype($file);
290                 if (! defined $type || $type=~/^_/) {
291                         error(sprintf(gettext("%s is not an editable page"), $page));
292                 }
293                 if (! $form->submitted) {
294                         $form->field(name => "rcsinfo",
295                                 value => rcs_prepedit($file), force => 1);
296                 }
297                 $form->field(name => "editcontent", validate => '/.*/');
298         }
299         else {
300                 $type=$form->param('type');
301                 if (defined $type && length $type && $hooks{htmlize}{$type}) {
302                         $type=possibly_foolish_untaint($type);
303                 }
304                 elsif (defined $from && exists $pagesources{$from}) {
305                         # favor the type of linking page
306                         $type=pagetype($pagesources{$from});
307                 }
308                 $type=$config{default_pageext} unless defined $type;
309                 $file=$page.".".$type;
310                 if (! $form->submitted) {
311                         $form->field(name => "rcsinfo", value => "", force => 1);
312                 }
313                 $form->field(name => "editcontent", validate => '/.+/');
314         }
316         $form->field(name => "do", type => 'hidden');
317         $form->field(name => "from", type => 'hidden');
318         $form->field(name => "rcsinfo", type => 'hidden');
319         $form->field(name => "subpage", type => 'hidden');
320         $form->field(name => "page", value => pagetitle($page, 1), force => 1);
321         $form->field(name => "type", value => $type, force => 1);
322         $form->field(name => "comments", type => "text", size => 80);
323         $form->field(name => "editcontent", type => "textarea", rows => 20,
324                 cols => 80);
325         $form->tmpl_param("can_commit", $config{rcs});
326         $form->tmpl_param("indexlink", indexlink());
327         $form->tmpl_param("helponformattinglink",
328                 htmllink("", "", "ikiwiki/formatting",
329                         noimageinline => 1,
330                         linktext => "FormattingHelp"));
331         $form->tmpl_param("baseurl", baseurl());
332         
333         if ($form->submitted eq "Cancel") {
334                 if ($form->field("do") eq "create" && defined $from) {
335                         redirect($q, "$config{url}/".htmlpage($from));
336                 }
337                 elsif ($form->field("do") eq "create") {
338                         redirect($q, $config{url});
339                 }
340                 else {
341                         redirect($q, "$config{url}/".htmlpage($page));
342                 }
343                 return;
344         }
345         elsif ($form->submitted eq "Preview") {
346                 my $content=$form->field('editcontent');
347                 run_hooks(editcontent => sub {
348                         $content=shift->(
349                                 content => $content,
350                                 page => $page,
351                                 cgi => $q,
352                                 session => $session,
353                         );
354                 });
355                 $form->tmpl_param("page_preview",
356                         htmlize($page, $type,
357                         linkify($page, "",
358                         preprocess($page, $page,
359                         filter($page, $page, $content), 0, 1))));
360                 # previewing may have created files on disk
361                 saveindex();
362         }
363         elsif ($form->submitted eq "Save Page") {
364                 $form->tmpl_param("page_preview", "");
365         }
366         $form->tmpl_param("page_conflict", "");
367         
368         if ($form->submitted ne "Save Page" || ! $form->validate) {
369                 if ($form->field("do") eq "create") {
370                         my @page_locs;
371                         my $best_loc;
372                         if (! defined $from || ! length $from ||
373                             $from ne $form->field('from') ||
374                             file_pruned($from, $config{srcdir}) ||
375                             $from=~/^\// ||
376                             $form->submitted eq "Preview") {
377                                 @page_locs=$best_loc=$page;
378                         }
379                         else {
380                                 my $dir=$from."/";
381                                 $dir=~s![^/]+/+$!!;
382                                 
383                                 if ((defined $form->field('subpage') && length $form->field('subpage')) ||
384                                     $page eq gettext('discussion')) {
385                                         $best_loc="$from/$page";
386                                 }
387                                 else {
388                                         $best_loc=$dir.$page;
389                                 }
390                                 
391                                 push @page_locs, $dir.$page;
392                                 push @page_locs, "$from/$page";
393                                 while (length $dir) {
394                                         $dir=~s![^/]+/+$!!;
395                                         push @page_locs, $dir.$page;
396                                 }
397                         }
398                         push @page_locs, "$config{userdir}/$page"
399                                 if length $config{userdir};
401                         @page_locs = grep {
402                                 ! exists $pagecase{lc $_}
403                         } @page_locs;
404                         if (! @page_locs) {
405                                 # hmm, someone else made the page in the
406                                 # meantime?
407                                 redirect($q, "$config{url}/".htmlpage($page));
408                                 return;
409                         }
411                         my @editable_locs = grep {
412                                 check_canedit($_, $q, $session, 1)
413                         } @page_locs;
414                         if (! @editable_locs) {
415                                 # let it throw an error this time
416                                 map { check_canedit($_, $q, $session) } @page_locs;
417                         }
418                         
419                         my @page_types;
420                         if (exists $hooks{htmlize}) {
421                                 @page_types=grep { !/^_/ }
422                                         keys %{$hooks{htmlize}};
423                         }
424                         
425                         $form->tmpl_param("page_select", 1);
426                         $form->field(name => "page", type => 'select',
427                                 options => [ map { pagetitle($_, 1) } @editable_locs ],
428                                 value => pagetitle($best_loc, 1));
429                         $form->field(name => "type", type => 'select',
430                                 options => \@page_types);
431                         $form->title(sprintf(gettext("creating %s"), pagetitle($page)));
432                         
433                 }
434                 elsif ($form->field("do") eq "edit") {
435                         check_canedit($page, $q, $session);
436                         if (! defined $form->field('editcontent') || 
437                             ! length $form->field('editcontent')) {
438                                 my $content="";
439                                 if (exists $pagesources{$page}) {
440                                         $content=readfile(srcfile($pagesources{$page}));
441                                         $content=~s/\n/\r\n/g;
442                                 }
443                                 $form->field(name => "editcontent", value => $content,
444                                         force => 1);
445                         }
446                         $form->tmpl_param("page_select", 0);
447                         $form->field(name => "page", type => 'hidden');
448                         $form->field(name => "type", type => 'hidden');
449                         $form->title(sprintf(gettext("editing %s"), pagetitle($page)));
450                 }
451                 
452                 showform($form, \@buttons, $session, $q);
453         }
454         else {
455                 # save page
456                 check_canedit($page, $q, $session);
458                 my $exists=-e "$config{srcdir}/$file";
460                 if ($form->field("do") ne "create" && ! $exists &&
461                     ! eval { srcfile($file) }) {
462                         $form->tmpl_param("page_gone", 1);
463                         $form->field(name => "do", value => "create", force => 1);
464                         $form->tmpl_param("page_select", 0);
465                         $form->field(name => "page", type => 'hidden');
466                         $form->field(name => "type", type => 'hidden');
467                         $form->title(sprintf(gettext("editing %s"), $page));
468                         showform($form, \@buttons, $session, $q);
469                         return;
470                 }
471                 elsif ($form->field("do") eq "create" && $exists) {
472                         $form->tmpl_param("creation_conflict", 1);
473                         $form->field(name => "do", value => "edit", force => 1);
474                         $form->tmpl_param("page_select", 0);
475                         $form->field(name => "page", type => 'hidden');
476                         $form->field(name => "type", type => 'hidden');
477                         $form->title(sprintf(gettext("editing %s"), $page));
478                         $form->field("editcontent", 
479                                 value => readfile("$config{srcdir}/$file").
480                                          "\n\n\n".$form->field("editcontent"),
481                                 force => 1);
482                         showform($form, \@buttons, $session, $q);
483                         return;
484                 }
485                 
486                 my $content=$form->field('editcontent');
487                 run_hooks(editcontent => sub {
488                         $content=shift->(
489                                 content => $content,
490                                 page => $page,
491                                 cgi => $q,
492                                 session => $session,
493                         );
494                 });
495                 $content=~s/\r\n/\n/g;
496                 $content=~s/\r/\n/g;
497                 $content.="\n" if $content !~ /\n$/;
499                 $config{cgi}=0; # avoid cgi error message
500                 eval { writefile($file, $config{srcdir}, $content) };
501                 $config{cgi}=1;
502                 if ($@) {
503                         $form->field(name => "rcsinfo", value => rcs_prepedit($file),
504                                 force => 1);
505                         $form->tmpl_param("failed_save", 1);
506                         $form->tmpl_param("error_message", $@);
507                         $form->field("editcontent", value => $content, force => 1);
508                         $form->tmpl_param("page_select", 0);
509                         $form->field(name => "page", type => 'hidden');
510                         $form->field(name => "type", type => 'hidden');
511                         $form->title(sprintf(gettext("editing %s"), $page));
512                         showform($form, \@buttons, $session, $q);
513                         return;
514                 }
515                 
516                 my $conflict;
517                 if ($config{rcs}) {
518                         my $message="";
519                         if (defined $form->field('comments') &&
520                             length $form->field('comments')) {
521                                 $message=$form->field('comments');
522                         }
523                         
524                         if (! $exists) {
525                                 rcs_add($file);
526                         }
528                         # Prevent deadlock with post-commit hook by
529                         # signaling to it that it should not try to
530                         # do anything.
531                         disable_commit_hook();
532                         $conflict=rcs_commit($file, $message,
533                                 $form->field("rcsinfo"),
534                                 $session->param("name"), $ENV{REMOTE_ADDR});
535                         enable_commit_hook();
536                         rcs_update();
537                 }
538                 
539                 # Refresh even if there was a conflict, since other changes
540                 # may have been committed while the post-commit hook was
541                 # disabled.
542                 require IkiWiki::Render;
543                 refresh();
544                 saveindex();
546                 if (defined $conflict) {
547                         $form->field(name => "rcsinfo", value => rcs_prepedit($file),
548                                 force => 1);
549                         $form->tmpl_param("page_conflict", 1);
550                         $form->field("editcontent", value => $conflict, force => 1);
551                         $form->field("do", "edit", force => 1);
552                         $form->tmpl_param("page_select", 0);
553                         $form->field(name => "page", type => 'hidden');
554                         $form->field(name => "type", type => 'hidden');
555                         $form->title(sprintf(gettext("editing %s"), $page));
556                         showform($form, \@buttons, $session, $q);
557                         return;
558                 }
559                 else {
560                         # The trailing question mark tries to avoid broken
561                         # caches and get the most recent version of the page.
562                         redirect($q, "$config{url}/".htmlpage($page)."?updated");
563                 }
564         }
565 } #}}}
567 sub cgi_getsession ($) { #{{{
568         my $q=shift;
570         eval q{use CGI::Session};
571         CGI::Session->name("ikiwiki_session_".encode_utf8($config{wikiname}));
572         
573         my $oldmask=umask(077);
574         my $session = CGI::Session->new("driver:DB_File", $q,
575                 { FileName => "$config{wikistatedir}/sessions.db" });
576         umask($oldmask);
578         return $session;
579 } #}}}
581 sub cgi_savesession ($) { #{{{
582         my $session=shift;
584         # Force session flush with safe umask.
585         my $oldmask=umask(077);
586         $session->flush;
587         umask($oldmask);
588 } #}}}
590 sub cgi (;$$) { #{{{
591         my $q=shift;
592         my $session=shift;
594         if (! $q) {
595                 eval q{use CGI};
596                 error($@) if $@;
597         
598                 $q=CGI->new;
599         
600                 run_hooks(cgi => sub { shift->($q) });
601         }
603         my $do=$q->param('do');
604         if (! defined $do || ! length $do) {
605                 my $error = $q->cgi_error;
606                 if ($error) {
607                         error("Request not processed: $error");
608                 }
609                 else {
610                         error("\"do\" parameter missing");
611                 }
612         }
613         
614         # Need to lock the wiki before getting a session.
615         lockwiki();
616         loadindex();
617         
618         if (! $session) {
619                 $session=cgi_getsession($q);
620         }
621         
622         # Auth hooks can sign a user in.
623         if ($do ne 'signin' && ! defined $session->param("name")) {
624                 run_hooks(auth => sub {
625                         shift->($q, $session)
626                 });
627                 if (defined $session->param("name")) {
628                         # Make sure whatever user was authed is in the
629                         # userinfo db.
630                         if (! userinfo_get($session->param("name"), "regdate")) {
631                                 userinfo_setall($session->param("name"), {
632                                         email => "",
633                                         password => "",
634                                         regdate => time,
635                                 }) || error("failed adding user");
636                         }
637                 }
638         }
639         
640         if (defined $session->param("name") &&
641             userinfo_get($session->param("name"), "banned")) {
642                 print $q->header(-status => "403 Forbidden");
643                 $session->delete();
644                 print gettext("You are banned.");
645                 cgi_savesession($session);
646         }
648         run_hooks(sessioncgi => sub { shift->($q, $session) });
650         if ($do eq 'signin') {
651                 cgi_signin($q, $session);
652                 cgi_savesession($session);
653         }
654         elsif ($do eq 'prefs') {
655                 cgi_prefs($q, $session);
656         }
657         elsif ($do eq 'create' || $do eq 'edit') {
658                 cgi_editpage($q, $session);
659         }
660         elsif (defined $session->param("postsignin") || $do eq 'postsignin') {
661                 cgi_postsignin($q, $session);
662         }
663         else {
664                 error("unknown do parameter");
665         }
666 } #}}}