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