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