]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/CGI.pm
changelog, close bug
[git.ikiwiki.info.git] / IkiWiki / CGI.pm
1 #!/usr/bin/perl
3 package IkiWiki;
5 use warnings;
6 use strict;
7 use IkiWiki;
8 use IkiWiki::UserInfo;
9 use open qw{:utf8 :std};
10 use Encode;
12 sub printheader ($) {
13         my $session=shift;
14         
15         if (($ENV{HTTPS} && lc $ENV{HTTPS} ne "off") || $config{sslcookie}) {
16                 print $session->header(-charset => 'utf-8',
17                         -cookie => $session->cookie(-httponly => 1, -secure => 1));
18         }
19         else {
20                 print $session->header(-charset => 'utf-8',
21                         -cookie => $session->cookie(-httponly => 1));
22         }
23 }
25 sub prepform {
26         my $form=shift;
27         my $buttons=shift;
28         my $session=shift;
29         my $cgi=shift;
31         if (exists $hooks{formbuilder}) {
32                 run_hooks(formbuilder => sub {
33                         shift->(form => $form, cgi => $cgi, session => $session,
34                                 buttons => $buttons);
35                 });
36         }
38         return $form;
39 }
41 sub showform ($$$$;@) {
42         my $form=prepform(@_);
43         shift;
44         my $buttons=shift;
45         my $session=shift;
46         my $cgi=shift;
48         printheader($session);
49         print cgitemplate($cgi, $form->title,
50                 $form->render(submit => $buttons), @_);
51 }
53 sub cgitemplate ($$$;@) {
54         my $cgi=shift;
55         my $title=shift;
56         my $content=shift;
57         my %params=@_;
58         
59         my $template=template("page.tmpl");
61         my $topurl = defined $cgi ? $cgi->url : $config{url};
63         my $page="";
64         if (exists $params{page}) {
65                 $page=delete $params{page};
66                 $params{forcebaseurl}=urlabs(urlto($page), $topurl);
67         }
68         run_hooks(pagetemplate => sub {
69                 shift->(
70                         page => $page,
71                         destpage => $page,
72                         template => $template,
73                 );
74         });
75         templateactions($template, "");
77         $template->param(
78                 dynamic => 1,
79                 title => $title,
80                 wikiname => $config{wikiname},
81                 content => $content,
82                 baseurl => urlabs(baseurl(), $topurl),
83                 html5 => $config{html5},
84                 %params,
85         );
86         
87         return $template->output;
88 }
90 sub redirect ($$) {
91         my $q=shift;
92         eval q{use URI};
93         my $url=URI->new(urlabs(shift, $q->url));
94         if (! $config{w3mmode}) {
95                 print $q->redirect($url);
96         }
97         else {
98                 print "Content-type: text/plain\n";
99                 print "W3m-control: GOTO $url\n\n";
100         }
103 sub decode_cgi_utf8 ($) {
104         # decode_form_utf8 method is needed for 5.01
105         if ($] < 5.01) {
106                 my $cgi = shift;
107                 foreach my $f ($cgi->param) {
108                         $cgi->param($f, map { decode_utf8 $_ } $cgi->param($f));
109                 }
110         }
113 sub safe_decode_utf8 ($) {
114     my $octets = shift;
115     # call decode_utf8 on >= 5.20 only if it's not already decoded,
116     # otherwise it balks, on < 5.20, always call it
117     if ($] < 5.02 || !Encode::is_utf8($octets)) {
118         return decode_utf8($octets);
119     }
120     else {
121         return $octets;
122     }
125 sub decode_form_utf8 ($) {
126         if ($] >= 5.01) {
127                 my $form = shift;
128                 foreach my $f ($form->field) {
129                         my @value=map { safe_decode_utf8($_) } $form->field($f);
130                         $form->field(name  => $f,
131                                      value => \@value,
132                                      force => 1,
133                         );
134                 }
135         }
138 # Check if the user is signed in. If not, redirect to the signin form and
139 # save their place to return to later.
140 sub needsignin ($$) {
141         my $q=shift;
142         my $session=shift;
144         if (! defined $session->param("name") ||
145             ! userinfo_get($session->param("name"), "regdate")) {
146                 $session->param(postsignin => $q->query_string);
147                 cgi_signin($q, $session);
148                 cgi_savesession($session);
149                 exit;
150         }
153 sub cgi_signin ($$;$) {
154         my $q=shift;
155         my $session=shift;
156         my $returnhtml=shift;
158         decode_cgi_utf8($q);
159         eval q{use CGI::FormBuilder};
160         error($@) if $@;
161         my $form = CGI::FormBuilder->new(
162                 title => "signin",
163                 name => "signin",
164                 charset => "utf-8",
165                 method => 'POST',
166                 required => 'NONE',
167                 javascript => 0,
168                 params => $q,
169                 action => cgiurl(),
170                 header => 0,
171                 template => {type => 'div'},
172                 stylesheet => 1,
173         );
174         my $buttons=["Login"];
175         
176         $form->field(name => "do", type => "hidden", value => "signin",
177                 force => 1);
178         
179         decode_form_utf8($form);
180         run_hooks(formbuilder_setup => sub {
181                 shift->(form => $form, cgi => $q, session => $session,
182                         buttons => $buttons);
183         });
184         decode_form_utf8($form);
186         if ($form->submitted) {
187                 $form->validate;
188         }
190         if ($returnhtml) {
191                 $form=prepform($form, $buttons, $session, $q);
192                 return $form->render(submit => $buttons);
193         }
195         showform($form, $buttons, $session, $q);
198 sub cgi_postsignin ($$) {
199         my $q=shift;
200         my $session=shift;
201         
202         # Continue with whatever was being done before the signin process.
203         if (defined $session->param("postsignin")) {
204                 my $postsignin=CGI->new($session->param("postsignin"));
205                 $session->clear("postsignin");
206                 cgi($postsignin, $session);
207                 cgi_savesession($session);
208                 exit;
209         }
210         else {
211                 if ($config{sslcookie} && ! $q->https()) {
212                         error(gettext("probable misconfiguration: sslcookie is set, but you are attempting to login via http, not https"));
213                 }
214                 else {
215                         error(gettext("login failed, perhaps you need to turn on cookies?"));
216                 }
217         }
220 sub cgi_prefs ($$) {
221         my $q=shift;
222         my $session=shift;
224         needsignin($q, $session);
225         decode_cgi_utf8($q);
226         
227         # The session id is stored on the form and checked to
228         # guard against CSRF.
229         my $sid=$q->param('sid');
230         if (! defined $sid) {
231                 $q->delete_all;
232         }
233         elsif ($sid ne $session->id) {
234                 error(gettext("Your login session has expired."));
235         }
237         eval q{use CGI::FormBuilder};
238         error($@) if $@;
239         my $form = CGI::FormBuilder->new(
240                 title => "preferences",
241                 name => "preferences",
242                 header => 0,
243                 charset => "utf-8",
244                 method => 'POST',
245                 validate => {
246                         email => 'EMAIL',
247                 },
248                 required => 'NONE',
249                 javascript => 0,
250                 params => $q,
251                 action => cgiurl(),
252                 template => {type => 'div'},
253                 stylesheet => 1,
254                 fieldsets => [
255                         [login => gettext("Login")],
256                         [preferences => gettext("Preferences")],
257                         [admin => gettext("Admin")]
258                 ],
259         );
260         my $buttons=["Save Preferences", "Logout", "Cancel"];
261         
262         decode_form_utf8($form);
263         run_hooks(formbuilder_setup => sub {
264                 shift->(form => $form, cgi => $q, session => $session,
265                         buttons => $buttons);
266         });
267         decode_form_utf8($form);
268         
269         $form->field(name => "do", type => "hidden", value => "prefs",
270                 force => 1);
271         $form->field(name => "sid", type => "hidden", value => $session->id,
272                 force => 1);
273         $form->field(name => "email", size => 50, fieldset => "preferences");
274         
275         my $user_name=$session->param("name");
277         if (! $form->submitted) {
278                 $form->field(name => "email", force => 1,
279                         value => userinfo_get($user_name, "email"));
280         }
281         
282         if ($form->submitted eq 'Logout') {
283                 $session->delete();
284                 redirect($q, baseurl(undef));
285                 return;
286         }
287         elsif ($form->submitted eq 'Cancel') {
288                 redirect($q, baseurl(undef));
289                 return;
290         }
291         elsif ($form->submitted eq 'Save Preferences' && $form->validate) {
292                 if (defined $form->field('email')) {
293                         userinfo_set($user_name, 'email', $form->field('email')) ||
294                                 error("failed to set email");
295                 }
297                 $form->text(gettext("Preferences saved."));
298         }
299         
300         showform($form, $buttons, $session, $q,
301                 prefsurl => "", # avoid showing the preferences link
302         );
305 sub cgi_custom_failure ($$$) {
306         my $q=shift;
307         my $httpstatus=shift;
308         my $message=shift;
310         print $q->header(
311                 -status => $httpstatus,
312                 -charset => 'utf-8',
313         );
314         print $message;
316         # Internet Explod^Hrer won't show custom 404 responses
317         # unless they're >= 512 bytes
318         print ' ' x 512;
320         exit;
323 sub check_banned ($$) {
324         my $q=shift;
325         my $session=shift;
327         my $banned=0;
328         my $name=$session->param("name");
329         if (defined $name && 
330             grep { $name eq $_ } @{$config{banned_users}}) {
331                 $banned=1;
332         }
334         foreach my $b (@{$config{banned_users}}) {
335                 if (pagespec_match("", $b,
336                         ip => $session->remote_addr(),
337                         name => defined $name ? $name : "",
338                 )) {
339                         $banned=1;
340                         last;
341                 }
342         }
344         if ($banned) {
345                 $session->delete();
346                 cgi_savesession($session);
347                 cgi_custom_failure(
348                         $q, "403 Forbidden",
349                         gettext("You are banned."));
350         }
353 sub cgi_getsession ($) {
354         my $q=shift;
356         eval q{use CGI::Session; use HTML::Entities};
357         error($@) if $@;
358         CGI::Session->name("ikiwiki_session_".encode_entities($config{wikiname}));
359         
360         my $oldmask=umask(077);
361         my $session = eval {
362                 CGI::Session->new("driver:DB_File", $q,
363                         { FileName => "$config{wikistatedir}/sessions.db" })
364         };
365         if (! $session || $@) {
366                 my $error = $@;
367                 error($error." ".CGI::Session->errstr());
368         }
369         
370         umask($oldmask);
372         return $session;
375 # To guard against CSRF, the user's session id (sid)
376 # can be stored on a form. This function will check
377 # (for logged in users) that the sid on the form matches
378 # the session id in the cookie.
379 sub checksessionexpiry ($$) {
380         my $q=shift;
381         my $session = shift;
383         if (defined $session->param("name")) {
384                 my $sid=$q->param('sid');
385                 if (! defined $sid || $sid ne $session->id) {
386                         error(gettext("Your login session has expired."));
387                 }
388         }
391 sub cgi_savesession ($) {
392         my $session=shift;
394         # Force session flush with safe umask.
395         my $oldmask=umask(077);
396         $session->flush;
397         umask($oldmask);
400 sub cgi (;$$) {
401         my $q=shift;
402         my $session=shift;
404         eval q{use CGI};
405         error($@) if $@;
406         $CGI::DISABLE_UPLOADS=$config{cgi_disable_uploads};
408         if (! $q) {
409                 binmode(STDIN);
410                 $q=CGI->new;
411                 binmode(STDIN, ":utf8");
412         
413                 run_hooks(cgi => sub { shift->($q) });
414         }
416         my $do=$q->param('do');
417         if (! defined $do || ! length $do) {
418                 my $error = $q->cgi_error;
419                 if ($error) {
420                         error("Request not processed: $error");
421                 }
422                 else {
423                         error("\"do\" parameter missing");
424                 }
425         }
427         # Need to lock the wiki before getting a session.
428         lockwiki();
429         loadindex();
430         
431         if (! $session) {
432                 $session=cgi_getsession($q);
433         }
434         
435         # Auth hooks can sign a user in.
436         if ($do ne 'signin' && ! defined $session->param("name")) {
437                 run_hooks(auth => sub {
438                         shift->($q, $session)
439                 });
440                 if (defined $session->param("name")) {
441                         # Make sure whatever user was authed is in the
442                         # userinfo db.
443                         if (! userinfo_get($session->param("name"), "regdate")) {
444                                 userinfo_setall($session->param("name"), {
445                                         email => defined $session->param("email") ? $session->param("email") : "",
446                                         password => "",
447                                         regdate => time,
448                                 }) || error("failed adding user");
449                         }
450                 }
451         }
452         
453         check_banned($q, $session);
454         
455         run_hooks(sessioncgi => sub { shift->($q, $session) });
457         if ($do eq 'signin') {
458                 cgi_signin($q, $session);
459                 cgi_savesession($session);
460         }
461         elsif ($do eq 'prefs') {
462                 cgi_prefs($q, $session);
463         }
464         elsif (defined $session->param("postsignin") || $do eq 'postsignin') {
465                 cgi_postsignin($q, $session);
466         }
467         else {
468                 error("unknown do parameter");
469         }
472 # Does not need to be called directly; all errors will go through here.
473 sub cgierror ($) {
474         my $message=shift;
476         print "Content-type: text/html\n\n";
477         print cgitemplate(undef, gettext("Error"),
478                 "<p class=\"error\">".gettext("Error").": $message</p>");
479         die $@;