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