]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/CGI.pm
mdwn: Enable footnotes by default when using Discount
[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 $page="";
62         if (exists $params{page}) {
63                 $page=delete $params{page};
64                 $params{forcebaseurl}=urlto($page);
65         }
66         run_hooks(pagetemplate => sub {
67                 shift->(
68                         page => $page,
69                         destpage => $page,
70                         template => $template,
71                 );
72         });
73         templateactions($template, "");
75         my $baseurl = baseurl();
77         $template->param(
78                 dynamic => 1,
79                 title => $title,
80                 wikiname => $config{wikiname},
81                 content => $content,
82                 baseurl => $baseurl,
83                 html5 => $config{html5},
84                 %params,
85         );
86         
87         return $template->output;
88 }
90 sub redirect ($$) {
91         my $q=shift;
92         eval q{use URI};
94         my $topurl;
95         if (defined $q && ! $config{w3mmode} && ! $config{reverse_proxy}) {
96                 $topurl = $q->url;
97         }
99         my $url=URI->new(urlabs(shift, $topurl));
100         if (! $config{w3mmode}) {
101                 print $q->redirect($url);
102         }
103         else {
104                 print "Content-type: text/plain\n";
105                 print "W3m-control: GOTO $url\n\n";
106         }
109 sub decode_cgi_utf8 ($) {
110         # decode_form_utf8 method is needed for 5.01
111         if ($] < 5.01) {
112                 my $cgi = shift;
113                 foreach my $f ($cgi->param) {
114                         $cgi->param($f, map { decode_utf8 $_ }
115                                 @{$cgi->param_fetch($f)});
116                 }
117         }
120 sub safe_decode_utf8 ($) {
121     my $octets = shift;
122     if (!Encode::is_utf8($octets)) {
123         return decode_utf8($octets);
124     }
125     else {
126         return $octets;
127     }
130 sub decode_form_utf8 ($) {
131         if ($] >= 5.01) {
132                 my $form = shift;
133                 foreach my $f ($form->field) {
134                         my @value=map { safe_decode_utf8($_) } $form->field($f);
135                         $form->field(name  => $f,
136                                      value => \@value,
137                                      force => 1,
138                         );
139                 }
140         }
143 # Check if the user is signed in. If not, redirect to the signin form and
144 # save their place to return to later.
145 sub needsignin ($$) {
146         my $q=shift;
147         my $session=shift;
149         if (! length $session->param("name") ||
150             ! userinfo_get($session->param("name"), "regdate")) {
151                 $session->param(postsignin => $q->query_string);
152                 cgi_signin($q, $session);
153                 cgi_savesession($session);
154                 exit;
155         }
158 sub cgi_signin ($$;$) {
159         my $q=shift;
160         my $session=shift;
161         my $returnhtml=shift;
163         decode_cgi_utf8($q);
164         eval q{use CGI::FormBuilder};
165         error($@) if $@;
166         my $form = CGI::FormBuilder->new(
167                 title => "signin",
168                 name => "signin",
169                 charset => "utf-8",
170                 method => 'POST',
171                 required => 'NONE',
172                 javascript => 0,
173                 params => $q,
174                 action => cgiurl(),
175                 header => 0,
176                 template => {type => 'div'},
177                 stylesheet => 1,
178         );
179         my $buttons=["Login"];
180         
181         $form->field(name => "do", type => "hidden", value => "signin",
182                 force => 1);
183         
184         decode_form_utf8($form);
185         run_hooks(formbuilder_setup => sub {
186                 shift->(form => $form, cgi => $q, session => $session,
187                         buttons => $buttons);
188         });
189         decode_form_utf8($form);
191         if ($form->submitted) {
192                 $form->validate;
193         }
195         if ($returnhtml) {
196                 $form=prepform($form, $buttons, $session, $q);
197                 return $form->render(submit => $buttons);
198         }
200         showform($form, $buttons, $session, $q);
203 sub cgi_postsignin ($$) {
204         my $q=shift;
205         my $session=shift;
206         
207         # Continue with whatever was being done before the signin process.
208         if (defined $session->param("postsignin")) {
209                 my $postsignin=CGI->new($session->param("postsignin"));
210                 $session->clear("postsignin");
211                 cgi($postsignin, $session);
212                 cgi_savesession($session);
213                 exit;
214         }
215         else {
216                 if ($config{sslcookie} && ! $q->https()) {
217                         error(gettext("probable misconfiguration: sslcookie is set, but you are attempting to login via http, not https"));
218                 }
219                 else {
220                         error(gettext("login failed, perhaps you need to turn on cookies?"));
221                 }
222         }
225 sub cgi_prefs ($$) {
226         my $q=shift;
227         my $session=shift;
229         needsignin($q, $session);
230         decode_cgi_utf8($q);
231         
232         # The session id is stored on the form and checked to
233         # guard against CSRF.
234         my $sid=$q->param('sid');
235         if (! defined $sid) {
236                 $q->delete_all;
237         }
238         elsif ($sid ne $session->id) {
239                 error(gettext("Your login session has expired."));
240         }
242         eval q{use CGI::FormBuilder};
243         error($@) if $@;
244         my $form = CGI::FormBuilder->new(
245                 title => "preferences",
246                 name => "preferences",
247                 header => 0,
248                 charset => "utf-8",
249                 method => 'POST',
250                 validate => {
251                         email => 'EMAIL',
252                 },
253                 required => 'NONE',
254                 javascript => 0,
255                 params => $q,
256                 action => cgiurl(),
257                 template => {type => 'div'},
258                 stylesheet => 1,
259                 fieldsets => [
260                         [login => gettext("Login")],
261                         [preferences => gettext("Preferences")],
262                         [admin => gettext("Admin")]
263                 ],
264         );
265         my $buttons=["Save Preferences", "Logout", "Cancel"];
266         
267         decode_form_utf8($form);
268         run_hooks(formbuilder_setup => sub {
269                 shift->(form => $form, cgi => $q, session => $session,
270                         buttons => $buttons);
271         });
272         decode_form_utf8($form);
273         
274         $form->field(name => "do", type => "hidden", value => "prefs",
275                 force => 1);
276         $form->field(name => "sid", type => "hidden", value => $session->id,
277                 force => 1);
278         $form->field(name => "email", size => 50, fieldset => "preferences");
279         
280         my $user_name=$session->param("name");
282         if (! $form->submitted) {
283                 $form->field(name => "email", force => 1,
284                         value => userinfo_get($user_name, "email"));
285         }
286         
287         if ($form->submitted eq 'Logout') {
288                 $session->delete();
289                 redirect($q, baseurl(undef));
290                 return;
291         }
292         elsif ($form->submitted eq 'Cancel') {
293                 redirect($q, baseurl(undef));
294                 return;
295         }
296         elsif ($form->submitted eq 'Save Preferences' && $form->validate) {
297                 my $email = $form->field('email');
298                 if (defined $email) {
299                         userinfo_set($user_name, 'email', $email) ||
300                                 error("failed to set email");
301                 }
303                 $form->text(gettext("Preferences saved."));
304         }
305         
306         showform($form, $buttons, $session, $q,
307                 prefsurl => "", # avoid showing the preferences link
308         );
311 sub cgi_custom_failure ($$$) {
312         my $q=shift;
313         my $httpstatus=shift;
314         my $message=shift;
316         print $q->header(
317                 -status => $httpstatus,
318                 -charset => 'utf-8',
319         );
320         print $message;
322         # Internet Explod^Hrer won't show custom 404 responses
323         # unless they're >= 512 bytes
324         print ' ' x 512;
326         exit;
329 sub check_banned ($$) {
330         my $q=shift;
331         my $session=shift;
333         my $banned=0;
334         my $name=$session->param("name");
335         my $cloak=cloak($name) if defined $name;
336         if (defined $name && 
337             grep { $name eq $_ || $cloak eq $_ } @{$config{banned_users}}) {
338                 $banned=1;
339         }
341         foreach my $b (@{$config{banned_users}}) {
342                 if (pagespec_match("", $b,
343                         ip => $session->remote_addr(),
344                         name => defined $name ? $name : "")
345                    || pagespec_match("", $b,
346                         ip => cloak($session->remote_addr()),
347                         name => defined $cloak ? $cloak : "")) {
348                         $banned=1;
349                         last;
350                 }
351         }
353         if ($banned) {
354                 $session->delete();
355                 cgi_savesession($session);
356                 cgi_custom_failure(
357                         $q, "403 Forbidden",
358                         gettext("You are banned."));
359         }
362 sub cgi_getsession ($) {
363         my $q=shift;
365         eval q{use CGI::Session; use HTML::Entities};
366         error($@) if $@;
367         CGI::Session->name("ikiwiki_session_".encode_entities($config{wikiname}));
368         
369         my $oldmask=umask(077);
370         my $session = eval {
371                 CGI::Session->new("driver:DB_File", $q,
372                         { FileName => "$config{wikistatedir}/sessions.db" })
373         };
374         if (! $session || $@) {
375                 my $error = $@;
376                 error($error." ".CGI::Session->errstr());
377         }
378         
379         umask($oldmask);
381         return $session;
384 # To guard against CSRF, the user's session id (sid)
385 # can be stored on a form. This function will check
386 # (for logged in users) that the sid on the form matches
387 # the session id in the cookie.
388 sub checksessionexpiry ($$) {
389         my $q=shift;
390         my $session = shift;
392         if (defined $session->param("name")) {
393                 my $sid=$q->param('sid');
394                 if (! defined $sid || $sid ne $session->id || ! length $session->param("name")) {
395                         error(gettext("Your login session has expired."));
396                 }
397         }
400 sub cgi_savesession ($) {
401         my $session=shift;
403         # Force session flush with safe umask.
404         my $oldmask=umask(077);
405         $session->flush;
406         umask($oldmask);
409 sub cgi (;$$) {
410         my $q=shift;
411         my $session=shift;
413         eval q{use CGI};
414         error($@) if $@;
415         no warnings "once";
416         $CGI::DISABLE_UPLOADS=$config{cgi_disable_uploads};
417         use warnings;
419         if (! $q) {
420                 binmode(STDIN);
421                 $q=CGI->new;
422                 binmode(STDIN, ":utf8");
423         
424                 run_hooks(cgi => sub { shift->($q) });
425         }
427         my $do=$q->param('do');
428         if (! defined $do || ! length $do) {
429                 my $error = $q->cgi_error;
430                 if ($error) {
431                         error("Request not processed: $error");
432                 }
433                 else {
434                         error("\"do\" parameter missing");
435                 }
436         }
438         # Need to lock the wiki before getting a session.
439         lockwiki();
440         loadindex();
441         
442         if (! $session) {
443                 $session=cgi_getsession($q);
444         }
445         
446         # Auth hooks can sign a user in.
447         if ($do ne 'signin' && ! length $session->param("name")) {
448                 run_hooks(auth => sub {
449                         shift->($q, $session)
450                 });
451                 if (length $session->param("name")) {
452                         # Make sure whatever user was authed is in the
453                         # userinfo db.
454                         if (! userinfo_get($session->param("name"), "regdate")) {
455                                 userinfo_setall($session->param("name"), {
456                                         email => defined $session->param("email") ? $session->param("email") : "",
457                                         password => "",
458                                         regdate => time,
459                                 }) || error("failed adding user");
460                         }
461                 }
462         }
463         
464         check_banned($q, $session);
465         
466         run_hooks(sessioncgi => sub { shift->($q, $session) });
468         if ($do eq 'signin') {
469                 cgi_signin($q, $session);
470                 cgi_savesession($session);
471         }
472         elsif ($do eq 'prefs') {
473                 cgi_prefs($q, $session);
474         }
475         elsif (defined $session->param("postsignin") || $do eq 'postsignin') {
476                 cgi_postsignin($q, $session);
477         }
478         else {
479                 error("unknown do parameter");
480         }
483 # Does not need to be called directly; all errors will go through here.
484 sub cgierror ($) {
485         my $message=shift;
487         eval q{use HTML::Entities};
488         $message = encode_entities($message);
490         print "Content-type: text/html\n\n";
491         print cgitemplate(undef, gettext("Error"),
492                 "<p class=\"error\">".gettext("Error").": $message</p>");
494         die $message;