01c5812ef03dd134c8078d40b25d7b6c1d066395
[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         eval q{use CGI 'escapeHTML'};
81
82         my $changelog=[rcs_recentchanges(100)];
83         foreach my $change (@$changelog) {
84                 $change->{when} = concise(ago($change->{when}));
85                 $change->{user} = htmllink("", "", escapeHTML($change->{user}), 1);
86                 $change->{pages} = [
87                         map {
88                                 $_->{link} = htmllink("", "", $_->{page}, 1);
89                                 $_;
90                         } @{$change->{pages}}
91                 ];
92         }
93
94         my $template=template("recentchanges.tmpl"); 
95         $template->param(
96                 title => "RecentChanges",
97                 indexlink => indexlink(),
98                 wikiname => $config{wikiname},
99                 changelog => $changelog,
100                 baseurl => baseurl(),
101         );
102         print $q->header(-charset => 'utf-8'), $template->output;
103 } #}}}
104
105 sub cgi_signin ($$) { #{{{
106         my $q=shift;
107         my $session=shift;
108
109         eval q{use CGI::FormBuilder};
110         my $form = CGI::FormBuilder->new(
111                 title => "signin",
112                 fields => [qw(do title page subpage from name password confirm_password email)],
113                 header => 1,
114                 charset => "utf-8",
115                 method => 'POST',
116                 validate => {
117                         confirm_password => {
118                                 perl => q{eq $form->field("password")},
119                         },
120                         email => 'EMAIL',
121                 },
122                 required => 'NONE',
123                 javascript => 0,
124                 params => $q,
125                 action => $config{cgiurl},
126                 header => 0,
127                 template => (-e "$config{templatedir}/signin.tmpl" ?
128                              {template_params("signin.tmpl")} : ""),
129                 stylesheet => baseurl()."style.css",
130         );
131                 
132         decode_form_utf8($form);
133         
134         $form->field(name => "name", required => 0);
135         $form->field(name => "do", type => "hidden");
136         $form->field(name => "page", type => "hidden");
137         $form->field(name => "title", type => "hidden");
138         $form->field(name => "from", type => "hidden");
139         $form->field(name => "subpage", type => "hidden");
140         $form->field(name => "password", type => "password", required => 0);
141         $form->field(name => "confirm_password", type => "password", required => 0);
142         $form->field(name => "email", required => 0);
143         if ($q->param("do") ne "signin" && !$form->submitted) {
144                 $form->text("You need to log in first.");
145         }
146         
147         if ($form->submitted) {
148                 # Set required fields based on how form was submitted.
149                 my %required=(
150                         "Login" => [qw(name password)],
151                         "Register" => [qw(name password confirm_password email)],
152                         "Mail Password" => [qw(name)],
153                 );
154                 foreach my $opt (@{$required{$form->submitted}}) {
155                         $form->field(name => $opt, required => 1);
156                 }
157         
158                 # Validate password differently depending on how
159                 # form was submitted.
160                 if ($form->submitted eq 'Login') {
161                         $form->field(
162                                 name => "password",
163                                 validate => sub {
164                                         length $form->field("name") &&
165                                         shift eq userinfo_get($form->field("name"), 'password');
166                                 },
167                         );
168                         $form->field(name => "name", validate => '/^\w+$/');
169                 }
170                 else {
171                         $form->field(name => "password", validate => 'VALUE');
172                 }
173                 # And make sure the entered name exists when logging
174                 # in or sending email, and does not when registering.
175                 if ($form->submitted eq 'Register') {
176                         $form->field(
177                                 name => "name",
178                                 validate => sub {
179                                         my $name=shift;
180                                         length $name &&
181                                         $name=~/$config{wiki_file_regexp}/ &&
182                                         ! userinfo_get($name, "regdate");
183                                 },
184                         );
185                 }
186                 else {
187                         $form->field(
188                                 name => "name",
189                                 validate => sub {
190                                         my $name=shift;
191                                         length $name &&
192                                         userinfo_get($name, "regdate");
193                                 },
194                         );
195                 }
196         }
197         else {
198                 # First time settings.
199                 $form->field(name => "name", comment => "use FirstnameLastName");
200                 $form->field(name => "confirm_password", comment => "(only needed");
201                 $form->field(name => "email",            comment => "for registration)");
202                 if ($session->param("name")) {
203                         $form->field(name => "name", value => $session->param("name"));
204                 }
205         }
206
207         if ($form->submitted && $form->validate) {
208                 if ($form->submitted eq 'Login') {
209                         $session->param("name", $form->field("name"));
210                         if (defined $form->field("do") && 
211                             $form->field("do") ne 'signin') {
212                                 redirect($q, cgiurl(
213                                         do => $form->field("do"),
214                                         page => $form->field("page"),
215                                         title => $form->field("title"),
216                                         subpage => $form->field("subpage"),
217                                         from => $form->field("from"),
218                                 ));
219                         }
220                         else {
221                                 redirect($q, $config{url});
222                         }
223                 }
224                 elsif ($form->submitted eq 'Register') {
225                         my $user_name=$form->field('name');
226                         if (userinfo_setall($user_name, {
227                                            'email' => $form->field('email'),
228                                            'password' => $form->field('password'),
229                                            'regdate' => time
230                                          })) {
231                                 $form->field(name => "confirm_password", type => "hidden");
232                                 $form->field(name => "email", type => "hidden");
233                                 $form->text("Registration successful. Now you can Login.");
234                                 printheader($session);
235                                 print misctemplate($form->title, $form->render(submit => ["Login"]));
236                         }
237                         else {
238                                 error("Error saving registration.");
239                         }
240                 }
241                 elsif ($form->submitted eq 'Mail Password') {
242                         my $user_name=$form->field("name");
243                         my $template=template("passwordmail.tmpl");
244                         $template->param(
245                                 user_name => $user_name,
246                                 user_password => userinfo_get($user_name, "password"),
247                                 wikiurl => $config{url},
248                                 wikiname => $config{wikiname},
249                                 REMOTE_ADDR => $ENV{REMOTE_ADDR},
250                         );
251                         
252                         eval q{use Mail::Sendmail};
253                         sendmail(
254                                 To => userinfo_get($user_name, "email"),
255                                 From => "$config{wikiname} admin <$config{adminemail}>",
256                                 Subject => "$config{wikiname} information",
257                                 Message => $template->output,
258                         ) or error("Failed to send mail");
259                         
260                         $form->text("Your password has been emailed to you.");
261                         $form->field(name => "name", required => 0);
262                         printheader($session);
263                         print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
264                 }
265         }
266         else {
267                 printheader($session);
268                 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
269         }
270 } #}}}
271
272 sub cgi_prefs ($$) { #{{{
273         my $q=shift;
274         my $session=shift;
275
276         eval q{use CGI::FormBuilder};
277         my $form = CGI::FormBuilder->new(
278                 title => "preferences",
279                 fields => [qw(do name password confirm_password email 
280                               subscriptions locked_pages)],
281                 header => 0,
282                 charset => "utf-8",
283                 method => 'POST',
284                 validate => {
285                         confirm_password => {
286                                 perl => q{eq $form->field("password")},
287                         },
288                         email => 'EMAIL',
289                 },
290                 required => 'NONE',
291                 javascript => 0,
292                 params => $q,
293                 action => $config{cgiurl},
294                 template => (-e "$config{templatedir}/prefs.tmpl" ?
295                              {template_params("prefs.tmpl")} : ""),
296                 stylesheet => baseurl()."style.css",
297         );
298         my @buttons=("Save Preferences", "Logout", "Cancel");
299         
300         my $user_name=$session->param("name");
301         $form->field(name => "do", type => "hidden");
302         $form->field(name => "name", disabled => 1,
303                 value => $user_name, force => 1);
304         $form->field(name => "password", type => "password");
305         $form->field(name => "confirm_password", type => "password");
306         $form->field(name => "subscriptions", size => 50,
307                 comment => "(".htmllink("", "", "PageSpec", 1).")");
308         $form->field(name => "locked_pages", size => 50,
309                 comment => "(".htmllink("", "", "PageSpec", 1).")");
310         
311         if (! is_admin($user_name)) {
312                 $form->field(name => "locked_pages", type => "hidden");
313         }
314         
315         if (! $form->submitted) {
316                 $form->field(name => "email", force => 1,
317                         value => userinfo_get($user_name, "email"));
318                 $form->field(name => "subscriptions", force => 1,
319                         value => userinfo_get($user_name, "subscriptions"));
320                 $form->field(name => "locked_pages", force => 1,
321                         value => userinfo_get($user_name, "locked_pages"));
322         }
323         
324         decode_form_utf8($form);
325         
326         if ($form->submitted eq 'Logout') {
327                 $session->delete();
328                 redirect($q, $config{url});
329                 return;
330         }
331         elsif ($form->submitted eq 'Cancel') {
332                 redirect($q, $config{url});
333                 return;
334         }
335         elsif ($form->submitted eq "Save Preferences" && $form->validate) {
336                 foreach my $field (qw(password email subscriptions locked_pages)) {
337                         if (length $form->field($field)) {
338                                 userinfo_set($user_name, $field, $form->field($field)) || error("failed to set $field");
339                         }
340                 }
341                 $form->text("Preferences saved.");
342         }
343         
344         printheader($session);
345         print misctemplate($form->title, $form->render(submit => \@buttons));
346 } #}}}
347
348 sub cgi_editpage ($$) { #{{{
349         my $q=shift;
350         my $session=shift;
351
352         eval q{use CGI::FormBuilder};
353         my $form = CGI::FormBuilder->new(
354                 fields => [qw(do rcsinfo subpage from page type editcontent comments)],
355                 header => 1,
356                 charset => "utf-8",
357                 method => 'POST',
358                 validate => {
359                         editcontent => '/.+/',
360                 },
361                 required => [qw{editcontent}],
362                 javascript => 0,
363                 params => $q,
364                 action => $config{cgiurl},
365                 table => 0,
366                 template => {template_params("editpage.tmpl")},
367         );
368         my @buttons=("Save Page", "Preview", "Cancel");
369         
370         decode_form_utf8($form);
371         
372         # This untaint is safe because titlepage removes any problematic
373         # characters.
374         my ($page)=$form->field('page');
375         $page=titlepage(possibly_foolish_untaint($page));
376         if (! defined $page || ! length $page ||
377             $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
378                 error("bad page name");
379         }
380         
381         my $from;
382         if (defined $form->field('from')) {
383                 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
384         }
385         
386         my $file;
387         my $type;
388         if (exists $pagesources{$page}) {
389                 $file=$pagesources{$page};
390                 $type=pagetype($file);
391         }
392         else {
393                 $type=$form->param('type');
394                 if (defined $type && length $type && $hooks{htmlize}{$type}) {
395                         $type=possibly_foolish_untaint($type);
396                 }
397                 elsif (defined $from) {
398                         # favor the type of linking page
399                         $type=pagetype($pagesources{$from});
400                 }
401                 $type=$config{default_pageext} unless defined $type;
402                 $file=$page.".".$type;
403         }
404
405         my $newfile=0;
406         if (! -e "$config{srcdir}/$file") {
407                 $newfile=1;
408         }
409
410         $form->field(name => "do", type => 'hidden');
411         $form->field(name => "from", type => 'hidden');
412         $form->field(name => "rcsinfo", type => 'hidden');
413         $form->field(name => "subpage", type => 'hidden');
414         $form->field(name => "page", value => $page, force => 1);
415         $form->field(name => "type", value => $type, force => 1);
416         $form->field(name => "comments", type => "text", size => 80);
417         $form->field(name => "editcontent", type => "textarea", rows => 20,
418                 cols => 80);
419         $form->tmpl_param("can_commit", $config{rcs});
420         $form->tmpl_param("indexlink", indexlink());
421         $form->tmpl_param("helponformattinglink",
422                 htmllink("", "", "HelpOnFormatting", 1));
423         $form->tmpl_param("baseurl", baseurl());
424         if (! $form->submitted) {
425                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
426                         force => 1);
427         }
428         
429         if ($form->submitted eq "Cancel") {
430                 redirect($q, "$config{url}/".htmlpage($page));
431                 return;
432         }
433         elsif ($form->submitted eq "Preview") {
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_".encode_utf8($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