New plugin: datetime_cmp
[ikiwiki.git] / IkiWiki / CGI.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use IkiWiki;
8 use IkiWiki::UserInfo;
9 use open qw{:utf8 :std};
10 use Encode;
11
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 }
24
25 sub prepform {
26         my $form=shift;
27         my $buttons=shift;
28         my $session=shift;
29         my $cgi=shift;
30
31         if (exists $hooks{formbuilder}) {
32                 run_hooks(formbuilder => sub {
33                         shift->(form => $form, cgi => $cgi, session => $session,
34                                 buttons => $buttons);
35                 });
36         }
37
38         return $form;
39 }
40
41 sub showform ($$$$;@) {
42         my $form=prepform(@_);
43         shift;
44         my $buttons=shift;
45         my $session=shift;
46         my $cgi=shift;
47
48         printheader($session);
49         print cgitemplate($cgi, $form->title,
50                 $form->render(submit => $buttons), @_);
51 }
52
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");
60
61         my $topurl = defined $cgi ? $cgi->url : $config{url};
62
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, "");
76
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 }
89
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         }
101 }
102
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         }
111 }
112
113 sub decode_form_utf8 ($) {
114         if ($] >= 5.01) {
115                 my $form = shift;
116                 foreach my $f ($form->field) {
117                         my @value=map { decode_utf8($_) } $form->field($f);
118                         $form->field(name  => $f,
119                                      value => \@value,
120                                      force => 1,
121                         );
122                 }
123         }
124 }
125
126 # Check if the user is signed in. If not, redirect to the signin form and
127 # save their place to return to later.
128 sub needsignin ($$) {
129         my $q=shift;
130         my $session=shift;
131
132         if (! defined $session->param("name") ||
133             ! userinfo_get($session->param("name"), "regdate")) {
134                 $session->param(postsignin => $q->query_string);
135                 cgi_signin($q, $session);
136                 cgi_savesession($session);
137                 exit;
138         }
139 }
140
141 sub cgi_signin ($$;$) {
142         my $q=shift;
143         my $session=shift;
144         my $returnhtml=shift;
145
146         decode_cgi_utf8($q);
147         eval q{use CGI::FormBuilder};
148         error($@) if $@;
149         my $form = CGI::FormBuilder->new(
150                 title => "signin",
151                 name => "signin",
152                 charset => "utf-8",
153                 method => 'POST',
154                 required => 'NONE',
155                 javascript => 0,
156                 params => $q,
157                 action => cgiurl(),
158                 header => 0,
159                 template => {type => 'div'},
160                 stylesheet => 1,
161         );
162         my $buttons=["Login"];
163         
164         $form->field(name => "do", type => "hidden", value => "signin",
165                 force => 1);
166         
167         decode_form_utf8($form);
168         run_hooks(formbuilder_setup => sub {
169                 shift->(form => $form, cgi => $q, session => $session,
170                         buttons => $buttons);
171         });
172         decode_form_utf8($form);
173
174         if ($form->submitted) {
175                 $form->validate;
176         }
177
178         if ($returnhtml) {
179                 $form=prepform($form, $buttons, $session, $q);
180                 return $form->render(submit => $buttons);
181         }
182
183         showform($form, $buttons, $session, $q);
184 }
185
186 sub cgi_postsignin ($$) {
187         my $q=shift;
188         my $session=shift;
189         
190         # Continue with whatever was being done before the signin process.
191         if (defined $session->param("postsignin")) {
192                 my $postsignin=CGI->new($session->param("postsignin"));
193                 $session->clear("postsignin");
194                 cgi($postsignin, $session);
195                 cgi_savesession($session);
196                 exit;
197         }
198         else {
199                 if ($config{sslcookie} && ! $q->https()) {
200                         error(gettext("probable misconfiguration: sslcookie is set, but you are attempting to login via http, not https"));
201                 }
202                 else {
203                         error(gettext("login failed, perhaps you need to turn on cookies?"));
204                 }
205         }
206 }
207
208 sub cgi_prefs ($$) {
209         my $q=shift;
210         my $session=shift;
211
212         needsignin($q, $session);
213         decode_cgi_utf8($q);
214         
215         # The session id is stored on the form and checked to
216         # guard against CSRF.
217         my $sid=$q->param('sid');
218         if (! defined $sid) {
219                 $q->delete_all;
220         }
221         elsif ($sid ne $session->id) {
222                 error(gettext("Your login session has expired."));
223         }
224
225         eval q{use CGI::FormBuilder};
226         error($@) if $@;
227         my $form = CGI::FormBuilder->new(
228                 title => "preferences",
229                 name => "preferences",
230                 header => 0,
231                 charset => "utf-8",
232                 method => 'POST',
233                 validate => {
234                         email => 'EMAIL',
235                 },
236                 required => 'NONE',
237                 javascript => 0,
238                 params => $q,
239                 action => cgiurl(),
240                 template => {type => 'div'},
241                 stylesheet => 1,
242                 fieldsets => [
243                         [login => gettext("Login")],
244                         [preferences => gettext("Preferences")],
245                         [admin => gettext("Admin")]
246                 ],
247         );
248         my $buttons=["Save Preferences", "Logout", "Cancel"];
249         
250         decode_form_utf8($form);
251         run_hooks(formbuilder_setup => sub {
252                 shift->(form => $form, cgi => $q, session => $session,
253                         buttons => $buttons);
254         });
255         decode_form_utf8($form);
256         
257         $form->field(name => "do", type => "hidden", value => "prefs",
258                 force => 1);
259         $form->field(name => "sid", type => "hidden", value => $session->id,
260                 force => 1);
261         $form->field(name => "email", size => 50, fieldset => "preferences");
262         
263         my $user_name=$session->param("name");
264
265         if (! $form->submitted) {
266                 $form->field(name => "email", force => 1,
267                         value => userinfo_get($user_name, "email"));
268         }
269         
270         if ($form->submitted eq 'Logout') {
271                 $session->delete();
272                 redirect($q, baseurl(undef));
273                 return;
274         }
275         elsif ($form->submitted eq 'Cancel') {
276                 redirect($q, baseurl(undef));
277                 return;
278         }
279         elsif ($form->submitted eq 'Save Preferences' && $form->validate) {
280                 if (defined $form->field('email')) {
281                         userinfo_set($user_name, 'email', $form->field('email')) ||
282                                 error("failed to set email");
283                 }
284
285                 $form->text(gettext("Preferences saved."));
286         }
287         
288         showform($form, $buttons, $session, $q,
289                 prefsurl => "", # avoid showing the preferences link
290         );
291 }
292
293 sub cgi_custom_failure ($$$) {
294         my $q=shift;
295         my $httpstatus=shift;
296         my $message=shift;
297
298         print $q->header(
299                 -status => $httpstatus,
300                 -charset => 'utf-8',
301         );
302         print $message;
303
304         # Internet Explod^Hrer won't show custom 404 responses
305         # unless they're >= 512 bytes
306         print ' ' x 512;
307
308         exit;
309 }
310
311 sub check_banned ($$) {
312         my $q=shift;
313         my $session=shift;
314
315         my $banned=0;
316         my $name=$session->param("name");
317         if (defined $name && 
318             grep { $name eq $_ } @{$config{banned_users}}) {
319                 $banned=1;
320         }
321
322         foreach my $b (@{$config{banned_users}}) {
323                 if (pagespec_match("", $b,
324                         ip => $session->remote_addr(),
325                         name => defined $name ? $name : "",
326                 )) {
327                         $banned=1;
328                         last;
329                 }
330         }
331
332         if ($banned) {
333                 $session->delete();
334                 cgi_savesession($session);
335                 cgi_custom_failure(
336                         $q, "403 Forbidden",
337                         gettext("You are banned."));
338         }
339 }
340
341 sub cgi_getsession ($) {
342         my $q=shift;
343
344         eval q{use CGI::Session; use HTML::Entities};
345         error($@) if $@;
346         CGI::Session->name("ikiwiki_session_".encode_entities($config{wikiname}));
347         
348         my $oldmask=umask(077);
349         my $session = eval {
350                 CGI::Session->new("driver:DB_File", $q,
351                         { FileName => "$config{wikistatedir}/sessions.db" })
352         };
353         if (! $session || $@) {
354                 my $error = $@;
355                 error($error." ".CGI::Session->errstr());
356         }
357         
358         umask($oldmask);
359
360         return $session;
361 }
362
363 # To guard against CSRF, the user's session id (sid)
364 # can be stored on a form. This function will check
365 # (for logged in users) that the sid on the form matches
366 # the session id in the cookie.
367 sub checksessionexpiry ($$) {
368         my $q=shift;
369         my $session = shift;
370
371         if (defined $session->param("name")) {
372                 my $sid=$q->param('sid');
373                 if (! defined $sid || $sid ne $session->id) {
374                         error(gettext("Your login session has expired."));
375                 }
376         }
377 }
378
379 sub cgi_savesession ($) {
380         my $session=shift;
381
382         # Force session flush with safe umask.
383         my $oldmask=umask(077);
384         $session->flush;
385         umask($oldmask);
386 }
387
388 sub cgi (;$$) {
389         my $q=shift;
390         my $session=shift;
391
392         eval q{use CGI};
393         error($@) if $@;
394         $CGI::DISABLE_UPLOADS=$config{cgi_disable_uploads};
395
396         if (! $q) {
397                 binmode(STDIN);
398                 $q=CGI->new;
399                 binmode(STDIN, ":utf8");
400         
401                 run_hooks(cgi => sub { shift->($q) });
402         }
403
404         my $do=$q->param('do');
405         if (! defined $do || ! length $do) {
406                 my $error = $q->cgi_error;
407                 if ($error) {
408                         error("Request not processed: $error");
409                 }
410                 else {
411                         error("\"do\" parameter missing");
412                 }
413         }
414
415         # Need to lock the wiki before getting a session.
416         lockwiki();
417         loadindex();
418         
419         if (! $session) {
420                 $session=cgi_getsession($q);
421         }
422         
423         # Auth hooks can sign a user in.
424         if ($do ne 'signin' && ! defined $session->param("name")) {
425                 run_hooks(auth => sub {
426                         shift->($q, $session)
427                 });
428                 if (defined $session->param("name")) {
429                         # Make sure whatever user was authed is in the
430                         # userinfo db.
431                         if (! userinfo_get($session->param("name"), "regdate")) {
432                                 userinfo_setall($session->param("name"), {
433                                         email => defined $session->param("email") ? $session->param("email") : "",
434                                         password => "",
435                                         regdate => time,
436                                 }) || error("failed adding user");
437                         }
438                 }
439         }
440         
441         check_banned($q, $session);
442         
443         run_hooks(sessioncgi => sub { shift->($q, $session) });
444
445         if ($do eq 'signin') {
446                 cgi_signin($q, $session);
447                 cgi_savesession($session);
448         }
449         elsif ($do eq 'prefs') {
450                 cgi_prefs($q, $session);
451         }
452         elsif (defined $session->param("postsignin") || $do eq 'postsignin') {
453                 cgi_postsignin($q, $session);
454         }
455         else {
456                 error("unknown do parameter");
457         }
458 }
459
460 # Does not need to be called directly; all errors will go through here.
461 sub cgierror ($) {
462         my $message=shift;
463
464         print "Content-type: text/html\n\n";
465         print cgitemplate(undef, gettext("Error"),
466                 "<p class=\"error\">".gettext("Error").": $message</p>");
467         die $@;
468 }
469
470 1