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