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