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