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