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