close
[ikiwiki.git] / IkiWiki / CGI.pm
blobcb4f395a063076a64e0c33e95d220f2f8581602f
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;
15 if ($ENV{HTTPS} || $config{sslcookie}) {
16 print $session->header(-charset => 'utf-8',
17 -cookie => $session->cookie(-httponly => 1, -secure => 1));
19 else {
20 print $session->header(-charset => 'utf-8',
21 -cookie => $session->cookie(-httponly => 1));
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 });
38 return $form;
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 cgitemplate($cgi, $form->title,
50 $form->render(submit => $buttons), @_);
53 sub cgitemplate ($$$;@) {
54 my $cgi=shift;
55 my $title=shift;
56 my $content=shift;
57 my %params=@_;
59 my $template=template("page.tmpl");
61 my $topurl = defined $cgi ? $cgi->url : $config{url};
63 my $page="";
64 if (exists $params{page}) {
65 $page=delete $params{page};
66 $params{forcebaseurl}=urlabs(urlto($page), $topurl);
68 run_hooks(pagetemplate => sub {
69 shift->(
70 page => $page,
71 destpage => $page,
72 template => $template,
74 });
75 templateactions($template, "");
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,
87 return $template->output;
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);
97 else {
98 print "Content-type: text/plain\n";
99 print "W3m-control: GOTO $url\n\n";
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));
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,
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;
132 if (! defined $session->param("name") ||
133 ! userinfo_get($session->param("name"), "regdate")) {
134 $session->param(postsignin => $ENV{QUERY_STRING});
135 cgi_signin($q, $session);
136 cgi_savesession($session);
137 exit;
141 sub cgi_signin ($$;$) {
142 my $q=shift;
143 my $session=shift;
144 my $returnhtml=shift;
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,
162 my $buttons=["Login"];
164 $form->field(name => "do", type => "hidden", value => "signin",
165 force => 1);
167 decode_form_utf8($form);
168 run_hooks(formbuilder_setup => sub {
169 shift->(form => $form, cgi => $q, session => $session,
170 buttons => $buttons);
172 decode_form_utf8($form);
174 if ($form->submitted) {
175 $form->validate;
178 if ($returnhtml) {
179 $form=prepform($form, $buttons, $session, $q);
180 return $form->render(submit => $buttons);
183 showform($form, $buttons, $session, $q);
186 sub cgi_postsignin ($$) {
187 my $q=shift;
188 my $session=shift;
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;
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"));
202 else {
203 error(gettext("login failed, perhaps you need to turn on cookies?"));
208 sub cgi_prefs ($$) {
209 my $q=shift;
210 my $session=shift;
212 needsignin($q, $session);
213 decode_cgi_utf8($q);
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;
221 elsif ($sid ne $session->id) {
222 error(gettext("Your login session has expired."));
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',
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")]
248 my $buttons=["Save Preferences", "Logout", "Cancel"];
250 decode_form_utf8($form);
251 run_hooks(formbuilder_setup => sub {
252 shift->(form => $form, cgi => $q, session => $session,
253 buttons => $buttons);
255 decode_form_utf8($form);
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");
263 my $user_name=$session->param("name");
265 if (! $form->submitted) {
266 $form->field(name => "email", force => 1,
267 value => userinfo_get($user_name, "email"));
270 if ($form->submitted eq 'Logout') {
271 $session->delete();
272 redirect($q, baseurl(undef));
273 return;
275 elsif ($form->submitted eq 'Cancel') {
276 redirect($q, baseurl(undef));
277 return;
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");
285 $form->text(gettext("Preferences saved."));
288 showform($form, $buttons, $session, $q,
289 prefsurl => "", # avoid showing the preferences link
293 sub cgi_custom_failure ($$$) {
294 my $q=shift;
295 my $httpstatus=shift;
296 my $message=shift;
298 print $q->header(
299 -status => $httpstatus,
300 -charset => 'utf-8',
302 print $message;
304 # Internet Explod^Hrer won't show custom 404 responses
305 # unless they're >= 512 bytes
306 print ' ' x 512;
308 exit;
311 sub check_banned ($$) {
312 my $q=shift;
313 my $session=shift;
315 my $banned=0;
316 my $name=$session->param("name");
317 if (defined $name &&
318 grep { $name eq $_ } @{$config{banned_users}}) {
319 $banned=1;
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;
332 if ($banned) {
333 $session->delete();
334 cgi_savesession($session);
335 cgi_custom_failure(
336 $q, "403 Forbidden",
337 gettext("You are banned."));
341 sub cgi_getsession ($) {
342 my $q=shift;
344 eval q{use CGI::Session; use HTML::Entities};
345 error($@) if $@;
346 CGI::Session->name("ikiwiki_session_".encode_entities($config{wikiname}));
348 my $oldmask=umask(077);
349 my $session = eval {
350 CGI::Session->new("driver:DB_File", $q,
351 { FileName => "$config{wikistatedir}/sessions.db" })
353 if (! $session || $@) {
354 error($@." ".CGI::Session->errstr());
357 umask($oldmask);
359 return $session;
362 # To guard against CSRF, the user's session id (sid)
363 # can be stored on a form. This function will check
364 # (for logged in users) that the sid on the form matches
365 # the session id in the cookie.
366 sub checksessionexpiry ($$) {
367 my $q=shift;
368 my $session = shift;
370 if (defined $session->param("name")) {
371 my $sid=$q->param('sid');
372 if (! defined $sid || $sid ne $session->id) {
373 error(gettext("Your login session has expired."));
378 sub cgi_savesession ($) {
379 my $session=shift;
381 # Force session flush with safe umask.
382 my $oldmask=umask(077);
383 $session->flush;
384 umask($oldmask);
387 sub cgi (;$$) {
388 my $q=shift;
389 my $session=shift;
391 eval q{use CGI};
392 error($@) if $@;
393 $CGI::DISABLE_UPLOADS=$config{cgi_disable_uploads};
395 if (! $q) {
396 binmode(STDIN);
397 $q=CGI->new;
398 binmode(STDIN, ":utf8");
400 run_hooks(cgi => sub { shift->($q) });
403 my $do=$q->param('do');
404 if (! defined $do || ! length $do) {
405 my $error = $q->cgi_error;
406 if ($error) {
407 error("Request not processed: $error");
409 else {
410 error("\"do\" parameter missing");
414 # Need to lock the wiki before getting a session.
415 lockwiki();
416 loadindex();
418 if (! $session) {
419 $session=cgi_getsession($q);
422 # Auth hooks can sign a user in.
423 if ($do ne 'signin' && ! defined $session->param("name")) {
424 run_hooks(auth => sub {
425 shift->($q, $session)
427 if (defined $session->param("name")) {
428 # Make sure whatever user was authed is in the
429 # userinfo db.
430 if (! userinfo_get($session->param("name"), "regdate")) {
431 userinfo_setall($session->param("name"), {
432 email => "",
433 password => "",
434 regdate => time,
435 }) || error("failed adding user");
440 check_banned($q, $session);
442 run_hooks(sessioncgi => sub { shift->($q, $session) });
444 if ($do eq 'signin') {
445 cgi_signin($q, $session);
446 cgi_savesession($session);
448 elsif ($do eq 'prefs') {
449 cgi_prefs($q, $session);
451 elsif (defined $session->param("postsignin") || $do eq 'postsignin') {
452 cgi_postsignin($q, $session);
454 else {
455 error("unknown do parameter");
459 # Does not need to be called directly; all errors will go through here.
460 sub cgierror ($) {
461 my $message=shift;
463 print "Content-type: text/html\n\n";
464 print cgitemplate(undef, gettext("Error"),
465 "<p class=\"error\">".gettext("Error").": $message</p>");
466 die $@;