]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/CGI.pm
Fix redirect to use a full url.
[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} || $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 misctemplate($form->title, $form->render(submit => $buttons), @_);
50 }
52 # Like showform, but the base url will be set to allow edit previews
53 # that use links relative to the specified page.
54 sub showform_preview ($$$$;@) {
55         my $form=shift;
56         my $buttons=shift;
57         my $session=shift;
58         my $cgi=shift;
59         my %params=@_;
61         # The base url needs to be a full URL, and urlto may return a path.
62         my $baseurl = absurl(urlto($params{page}), $cgi->url);
64         showform($form, $buttons, $session, $cgi, @_,
65                 forcebaseurl => $baseurl);
66 }
68 # Forces a partial url (path only) to absolute, using the same
69 # URL scheme as the CGI. Full URLs are left unchanged.
70 sub absurl ($$) {
71         my $partialurl=shift;
72         my $q=shift;
74         eval q{use URI};
75         return URI->new_abs($partialurl, $q);
76 }
78 sub redirect ($$) {
79         my $q=shift;
80         eval q{use URI};
81         my $url=URI->new(absurl(shift, $q));
82         if (! $config{w3mmode}) {
83                 print $q->redirect($url);
84         }
85         else {
86                 print "Content-type: text/plain\n";
87                 print "W3m-control: GOTO $url\n\n";
88         }
89 }
91 sub decode_cgi_utf8 ($) {
92         # decode_form_utf8 method is needed for 5.01
93         if ($] < 5.01) {
94                 my $cgi = shift;
95                 foreach my $f ($cgi->param) {
96                         $cgi->param($f, map { decode_utf8 $_ } $cgi->param($f));
97                 }
98         }
99 }
101 sub decode_form_utf8 ($) {
102         if ($] >= 5.01) {
103                 my $form = shift;
104                 foreach my $f ($form->field) {
105                         my @value=map { decode_utf8($_) } $form->field($f);
106                         $form->field(name  => $f,
107                                      value => \@value,
108                                      force => 1,
109                         );
110                 }
111         }
114 # Check if the user is signed in. If not, redirect to the signin form and
115 # save their place to return to later.
116 sub needsignin ($$) {
117         my $q=shift;
118         my $session=shift;
120         if (! defined $session->param("name") ||
121             ! userinfo_get($session->param("name"), "regdate")) {
122                 $session->param(postsignin => $ENV{QUERY_STRING});
123                 cgi_signin($q, $session);
124                 cgi_savesession($session);
125                 exit;
126         }
129 sub cgi_signin ($$;$) {
130         my $q=shift;
131         my $session=shift;
132         my $returnhtml=shift;
134         decode_cgi_utf8($q);
135         eval q{use CGI::FormBuilder};
136         error($@) if $@;
137         my $form = CGI::FormBuilder->new(
138                 title => "signin",
139                 name => "signin",
140                 charset => "utf-8",
141                 method => 'POST',
142                 required => 'NONE',
143                 javascript => 0,
144                 params => $q,
145                 action => cgiurl(),
146                 header => 0,
147                 template => {type => 'div'},
148                 stylesheet => 1,
149         );
150         my $buttons=["Login"];
151         
152         $form->field(name => "do", type => "hidden", value => "signin",
153                 force => 1);
154         
155         decode_form_utf8($form);
156         run_hooks(formbuilder_setup => sub {
157                 shift->(form => $form, cgi => $q, session => $session,
158                         buttons => $buttons);
159         });
160         decode_form_utf8($form);
162         if ($form->submitted) {
163                 $form->validate;
164         }
166         if ($returnhtml) {
167                 $form=prepform($form, $buttons, $session, $q);
168                 return $form->render(submit => $buttons);
169         }
171         showform($form, $buttons, $session, $q);
174 sub cgi_postsignin ($$) {
175         my $q=shift;
176         my $session=shift;
177         
178         # Continue with whatever was being done before the signin process.
179         if (defined $session->param("postsignin")) {
180                 my $postsignin=CGI->new($session->param("postsignin"));
181                 $session->clear("postsignin");
182                 cgi($postsignin, $session);
183                 cgi_savesession($session);
184                 exit;
185         }
186         else {
187                 if ($config{sslcookie} && ! $q->https()) {
188                         error(gettext("probable misconfiguration: sslcookie is set, but you are attempting to login via http, not https"));
189                 }
190                 else {
191                         error(gettext("login failed, perhaps you need to turn on cookies?"));
192                 }
193         }
196 sub cgi_prefs ($$) {
197         my $q=shift;
198         my $session=shift;
200         needsignin($q, $session);
201         decode_cgi_utf8($q);
202         
203         # The session id is stored on the form and checked to
204         # guard against CSRF.
205         my $sid=$q->param('sid');
206         if (! defined $sid) {
207                 $q->delete_all;
208         }
209         elsif ($sid ne $session->id) {
210                 error(gettext("Your login session has expired."));
211         }
213         eval q{use CGI::FormBuilder};
214         error($@) if $@;
215         my $form = CGI::FormBuilder->new(
216                 title => "preferences",
217                 name => "preferences",
218                 header => 0,
219                 charset => "utf-8",
220                 method => 'POST',
221                 validate => {
222                         email => 'EMAIL',
223                 },
224                 required => 'NONE',
225                 javascript => 0,
226                 params => $q,
227                 action => cgiurl(),
228                 template => {type => 'div'},
229                 stylesheet => 1,
230                 fieldsets => [
231                         [login => gettext("Login")],
232                         [preferences => gettext("Preferences")],
233                         [admin => gettext("Admin")]
234                 ],
235         );
236         my $buttons=["Save Preferences", "Logout", "Cancel"];
237         
238         decode_form_utf8($form);
239         run_hooks(formbuilder_setup => sub {
240                 shift->(form => $form, cgi => $q, session => $session,
241                         buttons => $buttons);
242         });
243         decode_form_utf8($form);
244         
245         $form->field(name => "do", type => "hidden", value => "prefs",
246                 force => 1);
247         $form->field(name => "sid", type => "hidden", value => $session->id,
248                 force => 1);
249         $form->field(name => "email", size => 50, fieldset => "preferences");
250         
251         my $user_name=$session->param("name");
253         if (! $form->submitted) {
254                 $form->field(name => "email", force => 1,
255                         value => userinfo_get($user_name, "email"));
256         }
257         
258         if ($form->submitted eq 'Logout') {
259                 $session->delete();
260                 redirect($q, baseurl(undef));
261                 return;
262         }
263         elsif ($form->submitted eq 'Cancel') {
264                 redirect($q, baseurl(undef));
265                 return;
266         }
267         elsif ($form->submitted eq 'Save Preferences' && $form->validate) {
268                 if (defined $form->field('email')) {
269                         userinfo_set($user_name, 'email', $form->field('email')) ||
270                                 error("failed to set email");
271                 }
273                 $form->text(gettext("Preferences saved."));
274         }
275         
276         showform($form, $buttons, $session, $q,
277                 prefsurl => "", # avoid showing the preferences link
278         );
281 sub cgi_custom_failure ($$$) {
282         my $q=shift;
283         my $httpstatus=shift;
284         my $message=shift;
286         print $q->header(
287                 -status => $httpstatus,
288                 -charset => 'utf-8',
289         );
290         print $message;
292         # Internet Explod^Hrer won't show custom 404 responses
293         # unless they're >= 512 bytes
294         print ' ' x 512;
296         exit;
299 sub check_banned ($$) {
300         my $q=shift;
301         my $session=shift;
303         my $banned=0;
304         my $name=$session->param("name");
305         if (defined $name && 
306             grep { $name eq $_ } @{$config{banned_users}}) {
307                 $banned=1;
308         }
310         foreach my $b (@{$config{banned_users}}) {
311                 if (pagespec_match("", $b,
312                         ip => $session->remote_addr(),
313                         name => defined $name ? $name : "",
314                 )) {
315                         $banned=1;
316                         last;
317                 }
318         }
320         if ($banned) {
321                 $session->delete();
322                 cgi_savesession($session);
323                 cgi_custom_failure(
324                         $q, "403 Forbidden",
325                         gettext("You are banned."));
326         }
329 sub cgi_getsession ($) {
330         my $q=shift;
332         eval q{use CGI::Session; use HTML::Entities};
333         error($@) if $@;
334         CGI::Session->name("ikiwiki_session_".encode_entities($config{wikiname}));
335         
336         my $oldmask=umask(077);
337         my $session = eval {
338                 CGI::Session->new("driver:DB_File", $q,
339                         { FileName => "$config{wikistatedir}/sessions.db" })
340         };
341         if (! $session || $@) {
342                 error($@." ".CGI::Session->errstr());
343         }
344         
345         umask($oldmask);
347         return $session;
350 # To guard against CSRF, the user's session id (sid)
351 # can be stored on a form. This function will check
352 # (for logged in users) that the sid on the form matches
353 # the session id in the cookie.
354 sub checksessionexpiry ($$) {
355         my $q=shift;
356         my $session = shift;
358         if (defined $session->param("name")) {
359                 my $sid=$q->param('sid');
360                 if (! defined $sid || $sid ne $session->id) {
361                         error(gettext("Your login session has expired."));
362                 }
363         }
366 sub cgi_savesession ($) {
367         my $session=shift;
369         # Force session flush with safe umask.
370         my $oldmask=umask(077);
371         $session->flush;
372         umask($oldmask);
375 sub cgi (;$$) {
376         my $q=shift;
377         my $session=shift;
379         eval q{use CGI};
380         error($@) if $@;
381         $CGI::DISABLE_UPLOADS=$config{cgi_disable_uploads};
383         if (! $q) {
384                 binmode(STDIN);
385                 $q=CGI->new;
386                 binmode(STDIN, ":utf8");
387         
388                 run_hooks(cgi => sub { shift->($q) });
389         }
391         my $do=$q->param('do');
392         if (! defined $do || ! length $do) {
393                 my $error = $q->cgi_error;
394                 if ($error) {
395                         error("Request not processed: $error");
396                 }
397                 else {
398                         error("\"do\" parameter missing");
399                 }
400         }
402         # Need to lock the wiki before getting a session.
403         lockwiki();
404         loadindex();
405         
406         if (! $session) {
407                 $session=cgi_getsession($q);
408         }
409         
410         # Auth hooks can sign a user in.
411         if ($do ne 'signin' && ! defined $session->param("name")) {
412                 run_hooks(auth => sub {
413                         shift->($q, $session)
414                 });
415                 if (defined $session->param("name")) {
416                         # Make sure whatever user was authed is in the
417                         # userinfo db.
418                         if (! userinfo_get($session->param("name"), "regdate")) {
419                                 userinfo_setall($session->param("name"), {
420                                         email => "",
421                                         password => "",
422                                         regdate => time,
423                                 }) || error("failed adding user");
424                         }
425                 }
426         }
427         
428         check_banned($q, $session);
429         
430         run_hooks(sessioncgi => sub { shift->($q, $session) });
432         if ($do eq 'signin') {
433                 cgi_signin($q, $session);
434                 cgi_savesession($session);
435         }
436         elsif ($do eq 'prefs') {
437                 cgi_prefs($q, $session);
438         }
439         elsif (defined $session->param("postsignin") || $do eq 'postsignin') {
440                 cgi_postsignin($q, $session);
441         }
442         else {
443                 error("unknown do parameter");
444         }
447 # Does not need to be called directly; all errors will go through here.
448 sub cgierror ($) {
449         my $message=shift;
451         print "Content-type: text/html\n\n";
452         print misctemplate(gettext("Error"),
453                 "<p class=\"error\">".gettext("Error").": $message</p>");
454         die $@;