]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/CGI.pm
Merge branch 'master' into debian-jessie-backports
[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 (! defined $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                 if (defined $form->field('email')) {
298                         userinfo_set($user_name, 'email', $form->field('email')) ||
299                                 error("failed to set email");
300                 }
302                 $form->text(gettext("Preferences saved."));
303         }
304         
305         showform($form, $buttons, $session, $q,
306                 prefsurl => "", # avoid showing the preferences link
307         );
310 sub cgi_custom_failure ($$$) {
311         my $q=shift;
312         my $httpstatus=shift;
313         my $message=shift;
315         print $q->header(
316                 -status => $httpstatus,
317                 -charset => 'utf-8',
318         );
319         print $message;
321         # Internet Explod^Hrer won't show custom 404 responses
322         # unless they're >= 512 bytes
323         print ' ' x 512;
325         exit;
328 sub check_banned ($$) {
329         my $q=shift;
330         my $session=shift;
332         my $banned=0;
333         my $name=$session->param("name");
334         my $cloak=cloak($name) if defined $name;
335         if (defined $name && 
336             grep { $name eq $_ || $cloak eq $_ } @{$config{banned_users}}) {
337                 $banned=1;
338         }
340         foreach my $b (@{$config{banned_users}}) {
341                 if (pagespec_match("", $b,
342                         ip => $session->remote_addr(),
343                         name => defined $name ? $name : "")
344                    || pagespec_match("", $b,
345                         ip => cloak($session->remote_addr()),
346                         name => defined $cloak ? $cloak : "")) {
347                         $banned=1;
348                         last;
349                 }
350         }
352         if ($banned) {
353                 $session->delete();
354                 cgi_savesession($session);
355                 cgi_custom_failure(
356                         $q, "403 Forbidden",
357                         gettext("You are banned."));
358         }
361 sub cgi_getsession ($) {
362         my $q=shift;
364         eval q{use CGI::Session; use HTML::Entities};
365         error($@) if $@;
366         CGI::Session->name("ikiwiki_session_".encode_entities($config{wikiname}));
367         
368         my $oldmask=umask(077);
369         my $session = eval {
370                 CGI::Session->new("driver:DB_File", $q,
371                         { FileName => "$config{wikistatedir}/sessions.db" })
372         };
373         if (! $session || $@) {
374                 my $error = $@;
375                 error($error." ".CGI::Session->errstr());
376         }
377         
378         umask($oldmask);
380         return $session;
383 # To guard against CSRF, the user's session id (sid)
384 # can be stored on a form. This function will check
385 # (for logged in users) that the sid on the form matches
386 # the session id in the cookie.
387 sub checksessionexpiry ($$) {
388         my $q=shift;
389         my $session = shift;
391         if (defined $session->param("name")) {
392                 my $sid=$q->param('sid');
393                 if (! defined $sid || $sid ne $session->id) {
394                         error(gettext("Your login session has expired."));
395                 }
396         }
399 sub cgi_savesession ($) {
400         my $session=shift;
402         # Force session flush with safe umask.
403         my $oldmask=umask(077);
404         $session->flush;
405         umask($oldmask);
408 sub cgi (;$$) {
409         my $q=shift;
410         my $session=shift;
412         eval q{use CGI};
413         error($@) if $@;
414         no warnings "once";
415         $CGI::DISABLE_UPLOADS=$config{cgi_disable_uploads};
416         use warnings;
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         eval q{use HTML::Entities};
487         $message = encode_entities($message);
489         print "Content-type: text/html\n\n";
490         print cgitemplate(undef, gettext("Error"),
491                 "<p class=\"error\">".gettext("Error").": $message</p>");
492         die $@;