toc: Add startlevel parameter. (kerravonsen)
[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 ($config{sslcookie}) {
16                 print $session->header(-charset => 'utf-8',
17                         -cookie => $session->cookie(-httponly => 1, -secure => 1));
18         } else {
19                 print $session->header(-charset => 'utf-8',
20                         -cookie => $session->cookie(-httponly => 1));
21         }
22 }
23
24 sub showform ($$$$;@) {
25         my $form=shift;
26         my $buttons=shift;
27         my $session=shift;
28         my $cgi=shift;
29
30         if (exists $hooks{formbuilder}) {
31                 run_hooks(formbuilder => sub {
32                         shift->(form => $form, cgi => $cgi, session => $session,
33                                 buttons => $buttons);
34                 });
35         }
36
37         printheader($session);
38         print misctemplate($form->title, $form->render(submit => $buttons), @_);
39 }
40
41 sub redirect ($$) {
42         my $q=shift;
43         eval q{use URI};
44         my $url=URI->new(shift);
45         if (! $config{w3mmode}) {
46                 print $q->redirect($url);
47         }
48         else {
49                 print "Content-type: text/plain\n";
50                 print "W3m-control: GOTO $url\n\n";
51         }
52 }
53
54 sub decode_cgi_utf8 ($) {
55         # decode_form_utf8 method is needed for 5.10
56         if ($] < 5.01) {
57                 my $cgi = shift;
58                 foreach my $f ($cgi->param) {
59                         $cgi->param($f, map { decode_utf8 $_ } $cgi->param($f));
60                 }
61         }
62 }
63
64 sub decode_form_utf8 ($) {
65         if ($] >= 5.01) {
66                 my $form = shift;
67                 foreach my $f ($form->field) {
68                         $form->field(name  => $f,
69                                      value => decode_utf8($form->field($f)),
70                                      force => 1,
71                         );
72                 }
73         }
74 }
75
76 # Check if the user is signed in. If not, redirect to the signin form and
77 # save their place to return to later.
78 sub needsignin ($$) {
79         my $q=shift;
80         my $session=shift;
81
82         if (! defined $session->param("name") ||
83             ! userinfo_get($session->param("name"), "regdate")) {
84                 $session->param(postsignin => $ENV{QUERY_STRING});
85                 cgi_signin($q, $session);
86                 cgi_savesession($session);
87                 exit;
88         }
89 }
90
91 sub cgi_signin ($$) {
92         my $q=shift;
93         my $session=shift;
94
95         decode_cgi_utf8($q);
96         eval q{use CGI::FormBuilder};
97         error($@) if $@;
98         my $form = CGI::FormBuilder->new(
99                 title => "signin",
100                 name => "signin",
101                 charset => "utf-8",
102                 method => 'POST',
103                 required => 'NONE',
104                 javascript => 0,
105                 params => $q,
106                 action => $config{cgiurl},
107                 header => 0,
108                 template => {type => 'div'},
109                 stylesheet => baseurl()."style.css",
110         );
111         my $buttons=["Login"];
112         
113         if ($q->param("do") ne "signin" && !$form->submitted) {
114                 $form->text(gettext("You need to log in first."));
115         }
116         $form->field(name => "do", type => "hidden", value => "signin",
117                 force => 1);
118         
119         decode_form_utf8($form);
120         run_hooks(formbuilder_setup => sub {
121                 shift->(form => $form, cgi => $q, session => $session,
122                         buttons => $buttons);
123         });
124         decode_form_utf8($form);
125
126         if ($form->submitted) {
127                 $form->validate;
128         }
129
130         showform($form, $buttons, $session, $q);
131 }
132
133 sub cgi_postsignin ($$) {
134         my $q=shift;
135         my $session=shift;
136         
137         # Continue with whatever was being done before the signin process.
138         if (defined $session->param("postsignin")) {
139                 my $postsignin=CGI->new($session->param("postsignin"));
140                 $session->clear("postsignin");
141                 cgi($postsignin, $session);
142                 cgi_savesession($session);
143                 exit;
144         }
145         else {
146                 if ($config{sslcookie} && ! $q->https()) {
147                         error(gettext("probable misconfiguration: sslcookie is set, but you are attempting to login via http, not https"));
148                 }
149                 else {
150                         error(gettext("login failed, perhaps you need to turn on cookies?"));
151                 }
152         }
153 }
154
155 sub cgi_prefs ($$) {
156         my $q=shift;
157         my $session=shift;
158
159         needsignin($q, $session);
160         decode_cgi_utf8($q);
161         
162         # The session id is stored on the form and checked to
163         # guard against CSRF.
164         my $sid=$q->param('sid');
165         if (! defined $sid) {
166                 $q->delete_all;
167         }
168         elsif ($sid ne $session->id) {
169                 error(gettext("Your login session has expired."));
170         }
171
172         eval q{use CGI::FormBuilder};
173         error($@) if $@;
174         my $form = CGI::FormBuilder->new(
175                 title => "preferences",
176                 name => "preferences",
177                 header => 0,
178                 charset => "utf-8",
179                 method => 'POST',
180                 validate => {
181                         email => 'EMAIL',
182                 },
183                 required => 'NONE',
184                 javascript => 0,
185                 params => $q,
186                 action => $config{cgiurl},
187                 template => {type => 'div'},
188                 stylesheet => baseurl()."style.css",
189                 fieldsets => [
190                         [login => gettext("Login")],
191                         [preferences => gettext("Preferences")],
192                         [admin => gettext("Admin")]
193                 ],
194         );
195         my $buttons=["Save Preferences", "Logout", "Cancel"];
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         $form->field(name => "do", type => "hidden", value => "prefs",
205                 force => 1);
206         $form->field(name => "sid", type => "hidden", value => $session->id,
207                 force => 1);
208         $form->field(name => "email", size => 50, fieldset => "preferences");
209         
210         my $user_name=$session->param("name");
211
212         if (! $form->submitted) {
213                 $form->field(name => "email", force => 1,
214                         value => userinfo_get($user_name, "email"));
215         }
216         
217         if ($form->submitted eq 'Logout') {
218                 $session->delete();
219                 redirect($q, $config{url});
220                 return;
221         }
222         elsif ($form->submitted eq 'Cancel') {
223                 redirect($q, $config{url});
224                 return;
225         }
226         elsif ($form->submitted eq 'Save Preferences' && $form->validate) {
227                 if (defined $form->field('email')) {
228                         userinfo_set($user_name, 'email', $form->field('email')) ||
229                                 error("failed to set email");
230                 }
231
232                 $form->text(gettext("Preferences saved."));
233         }
234         
235         showform($form, $buttons, $session, $q);
236 }
237
238 sub cgi_custom_failure ($$$) {
239         my $q=shift;
240         my $httpstatus=shift;
241         my $message=shift;
242
243         print $q->header(
244                 -status => $httpstatus,
245                 -charset => 'utf-8',
246         );
247         print $message;
248
249         # Internet Explod^Hrer won't show custom 404 responses
250         # unless they're >= 512 bytes
251         print ' ' x 512;
252
253         exit;
254 }
255
256 sub check_banned ($$) {
257         my $q=shift;
258         my $session=shift;
259
260         my $banned=0;
261         my $name=$session->param("name");
262         if (defined $name && 
263             grep { $name eq $_ } @{$config{banned_users}}) {
264                 $banned=1;
265         }
266
267         foreach my $b (@{$config{banned_users}}) {
268                 if (pagespec_match("", $b,
269                         ip => $ENV{REMOTE_ADDR},
270                         name => defined $name ? $name : "",
271                 )) {
272                         $banned=1;
273                         last;
274                 }
275         }
276
277         if ($banned) {
278                 $session->delete();
279                 cgi_savesession($session);
280                 cgi_custom_failure(
281                         $q, "403 Forbidden",
282                         gettext("You are banned."));
283         }
284 }
285
286 sub cgi_getsession ($) {
287         my $q=shift;
288
289         eval q{use CGI::Session; use HTML::Entities};
290         error($@) if $@;
291         CGI::Session->name("ikiwiki_session_".encode_entities($config{wikiname}));
292         
293         my $oldmask=umask(077);
294         my $session = eval {
295                 CGI::Session->new("driver:DB_File", $q,
296                         { FileName => "$config{wikistatedir}/sessions.db" })
297         };
298         if (! $session || $@) {
299                 error($@." ".CGI::Session->errstr());
300         }
301         
302         umask($oldmask);
303
304         return $session;
305 }
306
307 # To guard against CSRF, the user's session id (sid)
308 # can be stored on a form. This function will check
309 # (for logged in users) that the sid on the form matches
310 # the session id in the cookie.
311 sub checksessionexpiry ($$) {
312         my $q=shift;
313         my $session = shift;
314
315         if (defined $session->param("name")) {
316                 my $sid=$q->param('sid');
317                 if (! defined $sid || $sid ne $session->id) {
318                         error(gettext("Your login session has expired."));
319                 }
320         }
321 }
322
323 sub cgi_savesession ($) {
324         my $session=shift;
325
326         # Force session flush with safe umask.
327         my $oldmask=umask(077);
328         $session->flush;
329         umask($oldmask);
330 }
331
332 sub cgi (;$$) {
333         my $q=shift;
334         my $session=shift;
335
336         eval q{use CGI};
337         error($@) if $@;
338         $CGI::DISABLE_UPLOADS=$config{cgi_disable_uploads};
339
340         if (! $q) {
341                 binmode(STDIN);
342                 $q=CGI->new;
343                 binmode(STDIN, ":utf8");
344         
345                 run_hooks(cgi => sub { shift->($q) });
346         }
347
348         my $do=$q->param('do');
349         if (! defined $do || ! length $do) {
350                 my $error = $q->cgi_error;
351                 if ($error) {
352                         error("Request not processed: $error");
353                 }
354                 else {
355                         error("\"do\" parameter missing");
356                 }
357         }
358
359         # Need to lock the wiki before getting a session.
360         lockwiki();
361         loadindex();
362         
363         if (! $session) {
364                 $session=cgi_getsession($q);
365         }
366         
367         # Auth hooks can sign a user in.
368         if ($do ne 'signin' && ! defined $session->param("name")) {
369                 run_hooks(auth => sub {
370                         shift->($q, $session)
371                 });
372                 if (defined $session->param("name")) {
373                         # Make sure whatever user was authed is in the
374                         # userinfo db.
375                         if (! userinfo_get($session->param("name"), "regdate")) {
376                                 userinfo_setall($session->param("name"), {
377                                         email => "",
378                                         password => "",
379                                         regdate => time,
380                                 }) || error("failed adding user");
381                         }
382                 }
383         }
384         
385         check_banned($q, $session);
386         
387         run_hooks(sessioncgi => sub { shift->($q, $session) });
388
389         if ($do eq 'signin') {
390                 cgi_signin($q, $session);
391                 cgi_savesession($session);
392         }
393         elsif ($do eq 'prefs') {
394                 cgi_prefs($q, $session);
395         }
396         elsif (defined $session->param("postsignin") || $do eq 'postsignin') {
397                 cgi_postsignin($q, $session);
398         }
399         else {
400                 error("unknown do parameter");
401         }
402 }
403
404 # Does not need to be called directly; all errors will go through here.
405 sub cgierror ($) {
406         my $message=shift;
407
408         print "Content-type: text/html\n\n";
409         print misctemplate(gettext("Error"),
410                 "<p class=\"error\">".gettext("Error").": $message</p>");
411         die $@;
412 }
413
414 1