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