escaping fix from Emanuele Aina
[ikiwiki.git] / IkiWiki / CGI.pm
1 #!/usr/bin/perl
2
3 use warnings;
4 use strict;
5 use IkiWiki;
6 use IkiWiki::UserInfo;
7 use open qw{:utf8 :std};
8 use Encode;
9
10 package IkiWiki;
11
12 sub printheader ($) { #{{{
13         my $session=shift;
14         
15         if ($config{sslcookie}) {
16                 print $session->header(-charset => 'utf-8',
17                         -cookie => $session->cookie(-secure => 1));
18         } else {
19                 print $session->header(-charset => 'utf-8');
20         }
21
22 } #}}}
23
24 sub redirect ($$) { #{{{
25         my $q=shift;
26         my $url=shift;
27         if (! $config{w3mmode}) {
28                 print $q->redirect($url);
29         }
30         else {
31                 print "Content-type: text/plain\n";
32                 print "W3m-control: GOTO $url\n\n";
33         }
34 } #}}}
35
36 sub page_locked ($$;$) { #{{{
37         my $page=shift;
38         my $session=shift;
39         my $nonfatal=shift;
40         
41         my $user=$session->param("name");
42         return if defined $user && is_admin($user);
43
44         foreach my $admin (@{$config{adminuser}}) {
45                 my $locked_pages=userinfo_get($admin, "locked_pages");
46                 if (pagespec_match($page, userinfo_get($admin, "locked_pages"))) {
47                         return 1 if $nonfatal;
48                         error(htmllink("", "", $page, 1)." is locked by ".
49                               htmllink("", "", $admin, 1)." and cannot be edited.");
50                 }
51         }
52
53         return 0;
54 } #}}}
55
56 sub decode_form_utf8 ($) { #{{{
57         my $form = shift;
58         foreach my $f ($form->field) {
59                 next if Encode::is_utf8(scalar $form->field($f));
60                 $form->field(name  => $f,
61                              value => decode_utf8($form->field($f)),
62                              force => 1,
63                             );
64         }
65 } #}}}
66
67 sub cgi_recentchanges ($) { #{{{
68         my $q=shift;
69         
70         unlockwiki();
71
72         # Optimisation: building recentchanges means calculating lots of
73         # links. Memoizing htmllink speeds it up a lot (can't be memoized
74         # during page builds as the return values may change, but they
75         # won't here.)
76         eval q{use Memoize};
77         memoize("htmllink");
78
79         eval q{use Time::Duration};
80
81         my $changelog=[rcs_recentchanges(100)];
82         foreach my $change (@$changelog) {
83                 $change->{when} = concise(ago($change->{when}));
84                 $change->{user} = htmllink("", "", escapeHTML($change->{user}), 1);
85                 $change->{pages} = [
86                         map {
87                                 $_->{link} = htmllink("", "", $_->{page}, 1);
88                                 $_;
89                         } @{$change->{pages}}
90                 ];
91         }
92
93         my $template=template("recentchanges.tmpl"); 
94         $template->param(
95                 title => "RecentChanges",
96                 indexlink => indexlink(),
97                 wikiname => $config{wikiname},
98                 changelog => $changelog,
99                 baseurl => baseurl(),
100         );
101         print $q->header(-charset => 'utf-8'), $template->output;
102 } #}}}
103
104 sub cgi_signin ($$) { #{{{
105         my $q=shift;
106         my $session=shift;
107
108         eval q{use CGI::FormBuilder};
109         my $form = CGI::FormBuilder->new(
110                 title => "signin",
111                 fields => [qw(do title page subpage from name password confirm_password email)],
112                 header => 1,
113                 charset => "utf-8",
114                 method => 'POST',
115                 validate => {
116                         confirm_password => {
117                                 perl => q{eq $form->field("password")},
118                         },
119                         email => 'EMAIL',
120                 },
121                 required => 'NONE',
122                 javascript => 0,
123                 params => $q,
124                 action => $config{cgiurl},
125                 header => 0,
126                 template => (-e "$config{templatedir}/signin.tmpl" ?
127                              {template_params("signin.tmpl")} : ""),
128                 stylesheet => baseurl()."style.css",
129         );
130                 
131         decode_form_utf8($form);
132         
133         $form->field(name => "name", required => 0);
134         $form->field(name => "do", type => "hidden");
135         $form->field(name => "page", type => "hidden");
136         $form->field(name => "title", type => "hidden");
137         $form->field(name => "from", type => "hidden");
138         $form->field(name => "subpage", type => "hidden");
139         $form->field(name => "password", type => "password", required => 0);
140         $form->field(name => "confirm_password", type => "password", required => 0);
141         $form->field(name => "email", required => 0);
142         if ($q->param("do") ne "signin" && !$form->submitted) {
143                 $form->text("You need to log in first.");
144         }
145         
146         if ($form->submitted) {
147                 # Set required fields based on how form was submitted.
148                 my %required=(
149                         "Login" => [qw(name password)],
150                         "Register" => [qw(name password confirm_password email)],
151                         "Mail Password" => [qw(name)],
152                 );
153                 foreach my $opt (@{$required{$form->submitted}}) {
154                         $form->field(name => $opt, required => 1);
155                 }
156         
157                 # Validate password differently depending on how
158                 # form was submitted.
159                 if ($form->submitted eq 'Login') {
160                         $form->field(
161                                 name => "password",
162                                 validate => sub {
163                                         length $form->field("name") &&
164                                         shift eq userinfo_get($form->field("name"), 'password');
165                                 },
166                         );
167                         $form->field(name => "name", validate => '/^\w+$/');
168                 }
169                 else {
170                         $form->field(name => "password", validate => 'VALUE');
171                 }
172                 # And make sure the entered name exists when logging
173                 # in or sending email, and does not when registering.
174                 if ($form->submitted eq 'Register') {
175                         $form->field(
176                                 name => "name",
177                                 validate => sub {
178                                         my $name=shift;
179                                         length $name &&
180                                         $name=~/$config{wiki_file_regexp}/ &&
181                                         ! userinfo_get($name, "regdate");
182                                 },
183                         );
184                 }
185                 else {
186                         $form->field(
187                                 name => "name",
188                                 validate => sub {
189                                         my $name=shift;
190                                         length $name &&
191                                         userinfo_get($name, "regdate");
192                                 },
193                         );
194                 }
195         }
196         else {
197                 # First time settings.
198                 $form->field(name => "name", comment => "use FirstnameLastName");
199                 $form->field(name => "confirm_password", comment => "(only needed");
200                 $form->field(name => "email",            comment => "for registration)");
201                 if ($session->param("name")) {
202                         $form->field(name => "name", value => $session->param("name"));
203                 }
204         }
205
206         if ($form->submitted && $form->validate) {
207                 if ($form->submitted eq 'Login') {
208                         $session->param("name", $form->field("name"));
209                         if (defined $form->field("do") && 
210                             $form->field("do") ne 'signin') {
211                                 redirect($q, cgiurl(
212                                         do => $form->field("do"),
213                                         page => $form->field("page"),
214                                         title => $form->field("title"),
215                                         subpage => $form->field("subpage"),
216                                         from => $form->field("from"),
217                                 ));
218                         }
219                         else {
220                                 redirect($q, $config{url});
221                         }
222                 }
223                 elsif ($form->submitted eq 'Register') {
224                         my $user_name=$form->field('name');
225                         if (userinfo_setall($user_name, {
226                                            'email' => $form->field('email'),
227                                            'password' => $form->field('password'),
228                                            'regdate' => time
229                                          })) {
230                                 $form->field(name => "confirm_password", type => "hidden");
231                                 $form->field(name => "email", type => "hidden");
232                                 $form->text("Registration successful. Now you can Login.");
233                                 printheader($session);
234                                 print misctemplate($form->title, $form->render(submit => ["Login"]));
235                         }
236                         else {
237                                 error("Error saving registration.");
238                         }
239                 }
240                 elsif ($form->submitted eq 'Mail Password') {
241                         my $user_name=$form->field("name");
242                         my $template=template("passwordmail.tmpl");
243                         $template->param(
244                                 user_name => $user_name,
245                                 user_password => userinfo_get($user_name, "password"),
246                                 wikiurl => $config{url},
247                                 wikiname => $config{wikiname},
248                                 REMOTE_ADDR => $ENV{REMOTE_ADDR},
249                         );
250                         
251                         eval q{use Mail::Sendmail};
252                         sendmail(
253                                 To => userinfo_get($user_name, "email"),
254                                 From => "$config{wikiname} admin <$config{adminemail}>",
255                                 Subject => "$config{wikiname} information",
256                                 Message => $template->output,
257                         ) or error("Failed to send mail");
258                         
259                         $form->text("Your password has been emailed to you.");
260                         $form->field(name => "name", required => 0);
261                         printheader($session);
262                         print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
263                 }
264         }
265         else {
266                 printheader($session);
267                 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
268         }
269 } #}}}
270
271 sub cgi_prefs ($$) { #{{{
272         my $q=shift;
273         my $session=shift;
274
275         eval q{use CGI::FormBuilder};
276         my $form = CGI::FormBuilder->new(
277                 title => "preferences",
278                 fields => [qw(do name password confirm_password email 
279                               subscriptions locked_pages)],
280                 header => 0,
281                 charset => "utf-8",
282                 method => 'POST',
283                 validate => {
284                         confirm_password => {
285                                 perl => q{eq $form->field("password")},
286                         },
287                         email => 'EMAIL',
288                 },
289                 required => 'NONE',
290                 javascript => 0,
291                 params => $q,
292                 action => $config{cgiurl},
293                 template => (-e "$config{templatedir}/prefs.tmpl" ?
294                              {template_params("prefs.tmpl")} : ""),
295                 stylesheet => baseurl()."style.css",
296         );
297         my @buttons=("Save Preferences", "Logout", "Cancel");
298         
299         my $user_name=$session->param("name");
300         $form->field(name => "do", type => "hidden");
301         $form->field(name => "name", disabled => 1,
302                 value => $user_name, force => 1);
303         $form->field(name => "password", type => "password");
304         $form->field(name => "confirm_password", type => "password");
305         $form->field(name => "subscriptions", size => 50,
306                 comment => "(".htmllink("", "", "PageSpec", 1).")");
307         $form->field(name => "locked_pages", size => 50,
308                 comment => "(".htmllink("", "", "PageSpec", 1).")");
309         
310         if (! is_admin($user_name)) {
311                 $form->field(name => "locked_pages", type => "hidden");
312         }
313         
314         if (! $form->submitted) {
315                 $form->field(name => "email", force => 1,
316                         value => userinfo_get($user_name, "email"));
317                 $form->field(name => "subscriptions", force => 1,
318                         value => userinfo_get($user_name, "subscriptions"));
319                 $form->field(name => "locked_pages", force => 1,
320                         value => userinfo_get($user_name, "locked_pages"));
321         }
322         
323         decode_form_utf8($form);
324         
325         if ($form->submitted eq 'Logout') {
326                 $session->delete();
327                 redirect($q, $config{url});
328                 return;
329         }
330         elsif ($form->submitted eq 'Cancel') {
331                 redirect($q, $config{url});
332                 return;
333         }
334         elsif ($form->submitted eq "Save Preferences" && $form->validate) {
335                 foreach my $field (qw(password email subscriptions locked_pages)) {
336                         if (length $form->field($field)) {
337                                 userinfo_set($user_name, $field, $form->field($field)) || error("failed to set $field");
338                         }
339                 }
340                 $form->text("Preferences saved.");
341         }
342         
343         printheader($session);
344         print misctemplate($form->title, $form->render(submit => \@buttons));
345 } #}}}
346
347 sub cgi_editpage ($$) { #{{{
348         my $q=shift;
349         my $session=shift;
350
351         eval q{use CGI::FormBuilder};
352         my $form = CGI::FormBuilder->new(
353                 fields => [qw(do rcsinfo subpage from page type editcontent comments)],
354                 header => 1,
355                 charset => "utf-8",
356                 method => 'POST',
357                 validate => {
358                         editcontent => '/.+/',
359                 },
360                 required => [qw{editcontent}],
361                 javascript => 0,
362                 params => $q,
363                 action => $config{cgiurl},
364                 table => 0,
365                 template => {template_params("editpage.tmpl")},
366         );
367         my @buttons=("Save Page", "Preview", "Cancel");
368         
369         decode_form_utf8($form);
370         
371         # This untaint is safe because titlepage removes any problematic
372         # characters.
373         my ($page)=$form->field('page');
374         $page=titlepage(possibly_foolish_untaint($page));
375         if (! defined $page || ! length $page ||
376             $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
377                 error("bad page name");
378         }
379         
380         my $from;
381         if (defined $form->field('from')) {
382                 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
383         }
384         
385         my $file;
386         my $type;
387         if (exists $pagesources{$page}) {
388                 $file=$pagesources{$page};
389                 $type=pagetype($file);
390         }
391         else {
392                 $type=$form->param('type');
393                 if (defined $type && length $type && $hooks{htmlize}{$type}) {
394                         $type=possibly_foolish_untaint($type);
395                 }
396                 elsif (defined $from) {
397                         # favor the type of linking page
398                         $type=pagetype($pagesources{$from});
399                 }
400                 $type=$config{default_pageext} unless defined $type;
401                 $file=$page.".".$type;
402         }
403
404         my $newfile=0;
405         if (! -e "$config{srcdir}/$file") {
406                 $newfile=1;
407         }
408
409         $form->field(name => "do", type => 'hidden');
410         $form->field(name => "from", type => 'hidden');
411         $form->field(name => "rcsinfo", type => 'hidden');
412         $form->field(name => "subpage", type => 'hidden');
413         $form->field(name => "page", value => $page, force => 1);
414         $form->field(name => "type", value => $type, force => 1);
415         $form->field(name => "comments", type => "text", size => 80);
416         $form->field(name => "editcontent", type => "textarea", rows => 20,
417                 cols => 80);
418         $form->tmpl_param("can_commit", $config{rcs});
419         $form->tmpl_param("indexlink", indexlink());
420         $form->tmpl_param("helponformattinglink",
421                 htmllink("", "", "HelpOnFormatting", 1));
422         $form->tmpl_param("baseurl", baseurl());
423         if (! $form->submitted) {
424                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
425                         force => 1);
426         }
427         
428         if ($form->submitted eq "Cancel") {
429                 redirect($q, "$config{url}/".htmlpage($page));
430                 return;
431         }
432         elsif ($form->submitted eq "Preview") {
433                 require IkiWiki::Render;
434                 my $content=$form->field('editcontent');
435                 my $comments=$form->field('comments');
436                 $form->field(name => "editcontent",
437                                 value => $content, force => 1);
438                 $form->field(name => "comments",
439                                 value => $comments, force => 1);
440                 $config{rss}=0; # avoid preview writing an rss feed!
441                 $form->tmpl_param("page_preview",
442                         htmlize($page, $type,
443                         linkify($page, "",
444                         preprocess($page, $page,
445                         filter($page, $content)))));
446         }
447         else {
448                 $form->tmpl_param("page_preview", "");
449         }
450         $form->tmpl_param("page_conflict", "");
451         
452         if (! $form->submitted || $form->submitted eq "Preview" || 
453             ! $form->validate) {
454                 if ($form->field("do") eq "create") {
455                         my @page_locs;
456                         my $best_loc;
457                         if (! defined $from || ! length $from ||
458                             $from ne $form->field('from') ||
459                             $from=~/$config{wiki_file_prune_regexp}/ ||
460                             $from=~/^\// ||
461                             $form->submitted eq "Preview") {
462                                 @page_locs=$best_loc=$page;
463                         }
464                         else {
465                                 my $dir=$from."/";
466                                 $dir=~s![^/]+/+$!!;
467                                 
468                                 if ((defined $form->field('subpage') && length $form->field('subpage')) ||
469                                     $page eq 'discussion') {
470                                         $best_loc="$from/$page";
471                                 }
472                                 else {
473                                         $best_loc=$dir.$page;
474                                 }
475                                 
476                                 push @page_locs, $dir.$page;
477                                 push @page_locs, "$from/$page";
478                                 while (length $dir) {
479                                         $dir=~s![^/]+/+$!!;
480                                         push @page_locs, $dir.$page;
481                                 }
482                         }
483
484                         @page_locs = grep {
485                                 ! exists $pagecase{lc $_} &&
486                                 ! page_locked($_, $session, 1)
487                         } @page_locs;
488                         
489                         if (! @page_locs) {
490                                 # hmm, someone else made the page in the
491                                 # meantime?
492                                 redirect($q, "$config{url}/".htmlpage($page));
493                                 return;
494                         }
495                         
496                         my @page_types;
497                         if (exists $hooks{htmlize}) {
498                                 @page_types=keys %{$hooks{htmlize}};
499                         }
500                         
501                         $form->tmpl_param("page_select", 1);
502                         $form->field(name => "page", type => 'select',
503                                 options => \@page_locs, value => $best_loc);
504                         $form->field(name => "type", type => 'select',
505                                 options => \@page_types);
506                         $form->title("creating ".pagetitle($page));
507                 }
508                 elsif ($form->field("do") eq "edit") {
509                         page_locked($page, $session);
510                         if (! defined $form->field('editcontent') || 
511                             ! length $form->field('editcontent')) {
512                                 my $content="";
513                                 if (exists $pagesources{$page}) {
514                                         $content=readfile(srcfile($pagesources{$page}));
515                                         $content=~s/\n/\r\n/g;
516                                 }
517                                 $form->field(name => "editcontent", value => $content,
518                                         force => 1);
519                         }
520                         $form->tmpl_param("page_select", 0);
521                         $form->field(name => "page", type => 'hidden');
522                         $form->field(name => "type", type => 'hidden');
523                         $form->title("editing ".pagetitle($page));
524                 }
525                 
526                 print $form->render(submit => \@buttons);
527         }
528         else {
529                 # save page
530                 page_locked($page, $session);
531                 
532                 my $content=$form->field('editcontent');
533
534                 $content=~s/\r\n/\n/g;
535                 $content=~s/\r/\n/g;
536                 writefile($file, $config{srcdir}, $content);
537                 
538                 my $message="web commit ";
539                 if (defined $session->param("name") && 
540                     length $session->param("name")) {
541                         $message.="by ".$session->param("name");
542                 }
543                 else {
544                         $message.="from $ENV{REMOTE_ADDR}";
545                 }
546                 if (defined $form->field('comments') &&
547                     length $form->field('comments')) {
548                         $message.=": ".$form->field('comments');
549                 }
550                 
551                 if ($config{rcs}) {
552                         if ($newfile) {
553                                 rcs_add($file);
554                         }
555                         # prevent deadlock with post-commit hook
556                         unlockwiki();
557                         # presumably the commit will trigger an update
558                         # of the wiki
559                         my $conflict=rcs_commit($file, $message,
560                                 $form->field("rcsinfo"));
561                 
562                         if (defined $conflict) {
563                                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
564                                         force => 1);
565                                 $form->tmpl_param("page_conflict", 1);
566                                 $form->field("editcontent", value => $conflict, force => 1);
567                                 $form->field(name => "comments", value => $form->field('comments'), force => 1);
568                                 $form->field("do", "edit)");
569                                 $form->tmpl_param("page_select", 0);
570                                 $form->field(name => "page", type => 'hidden');
571                                 $form->field(name => "type", type => 'hidden');
572                                 $form->title("editing $page");
573                                 print $form->render(submit => \@buttons);
574                                 return;
575                         }
576                 }
577                 else {
578                         require IkiWiki::Render;
579                         refresh();
580                         saveindex();
581                 }
582                 
583                 # The trailing question mark tries to avoid broken
584                 # caches and get the most recent version of the page.
585                 redirect($q, "$config{url}/".htmlpage($page)."?updated");
586         }
587 } #}}}
588
589 sub cgi () { #{{{
590         eval q{use CGI};
591         eval q{use CGI::Session};
592         
593         my $q=CGI->new;
594         
595         run_hooks(cgi => sub { shift->($q) });
596         
597         my $do=$q->param('do');
598         if (! defined $do || ! length $do) {
599                 my $error = $q->cgi_error;
600                 if ($error) {
601                         error("Request not processed: $error");
602                 }
603                 else {
604                         error("\"do\" parameter missing");
605                 }
606         }
607         
608         # Things that do not need a session.
609         if ($do eq 'recentchanges') {
610                 cgi_recentchanges($q);
611                 return;
612         }
613         elsif ($do eq 'hyperestraier') {
614                 cgi_hyperestraier();
615         }
616         
617         CGI::Session->name("ikiwiki_session_$config{wikiname}");
618         
619         my $oldmask=umask(077);
620         my $session = CGI::Session->new("driver:DB_File", $q,
621                 { FileName => "$config{wikistatedir}/sessions.db" });
622         umask($oldmask);
623         
624         # Everything below this point needs the user to be signed in.
625         if (((! $config{anonok} || $do eq 'prefs') &&
626              (! defined $session->param("name") ||
627              ! userinfo_get($session->param("name"), "regdate"))) || $do eq 'signin') {
628                 cgi_signin($q, $session);
629         
630                 # Force session flush with safe umask.
631                 my $oldmask=umask(077);
632                 $session->flush;
633                 umask($oldmask);
634                 
635                 return;
636         }
637         
638         if ($do eq 'create' || $do eq 'edit') {
639                 cgi_editpage($q, $session);
640         }
641         elsif ($do eq 'prefs') {
642                 cgi_prefs($q, $session);
643         }
644         elsif ($do eq 'blog') {
645                 my $page=titlepage(decode_utf8($q->param('title')));
646                 # if the page already exists, munge it to be unique
647                 my $from=$q->param('from');
648                 my $add="";
649                 while (exists $pagecase{lc "$from/$page$add"}) {
650                         $add=1 unless length $add;
651                         $add++;
652                 }
653                 $q->param('page', $page.$add);
654                 # now run same as create
655                 $q->param('do', 'create');
656                 cgi_editpage($q, $session);
657         }
658         else {
659                 error("unknown do parameter");
660         }
661 } #}}}
662
663 1