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