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