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