* Patch from Recai to limit recentchanges to displaying max 10 files for a
[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         
318         if (! is_admin($user_name)) {
319                 $form->field(name => "locked_pages", type => "hidden");
320         }
321
322         if ($config{httpauth}) {
323                 $form->field(name => "password", type => "hidden");
324                 $form->field(name => "confirm_password", type => "hidden");
325         }
326         
327         if (! $form->submitted) {
328                 $form->field(name => "email", force => 1,
329                         value => userinfo_get($user_name, "email"));
330                 $form->field(name => "subscriptions", force => 1,
331                         value => userinfo_get($user_name, "subscriptions"));
332                 $form->field(name => "locked_pages", force => 1,
333                         value => userinfo_get($user_name, "locked_pages"));
334         }
335         
336         decode_form_utf8($form);
337         
338         if ($form->submitted eq 'Logout') {
339                 $session->delete();
340                 redirect($q, $config{url});
341                 return;
342         }
343         elsif ($form->submitted eq 'Cancel') {
344                 redirect($q, $config{url});
345                 return;
346         }
347         elsif ($form->submitted eq "Save Preferences" && $form->validate) {
348                 foreach my $field (qw(password email subscriptions locked_pages)) {
349                         if (length $form->field($field)) {
350                                 userinfo_set($user_name, $field, $form->field($field)) || error("failed to set $field");
351                         }
352                 }
353                 $form->text("Preferences saved.");
354         }
355         
356         printheader($session);
357         print misctemplate($form->title, $form->render(submit => \@buttons));
358 } #}}}
359
360 sub cgi_editpage ($$) { #{{{
361         my $q=shift;
362         my $session=shift;
363
364         my @fields=qw(do rcsinfo subpage from page type editcontent comments);
365         my @buttons=("Save Page", "Preview", "Cancel");
366         
367         eval q{use CGI::FormBuilder; use CGI::FormBuilder::Template::HTML};
368         my $renderer=CGI::FormBuilder::Template::HTML->new(
369                 fields => \@fields,
370                 template_params("editpage.tmpl"),
371         );
372         run_hooks(pagetemplate => sub {
373                 shift->(page => "", destpage => "", template => $renderer->engine);
374         });
375         my $form = CGI::FormBuilder->new(
376                 fields => \@fields,
377                 header => 1,
378                 charset => "utf-8",
379                 method => 'POST',
380                 validate => {
381                         editcontent => '/.+/',
382                 },
383                 required => [qw{editcontent}],
384                 javascript => 0,
385                 params => $q,
386                 action => $config{cgiurl},
387                 table => 0,
388                 template => $renderer,
389         );
390         
391         decode_form_utf8($form);
392         
393         # This untaint is safe because titlepage removes any problematic
394         # characters.
395         my ($page)=$form->field('page');
396         $page=titlepage(possibly_foolish_untaint($page));
397         if (! defined $page || ! length $page ||
398             $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
399                 error("bad page name");
400         }
401         
402         my $from;
403         if (defined $form->field('from')) {
404                 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
405         }
406         
407         my $file;
408         my $type;
409         if (exists $pagesources{$page}) {
410                 $file=$pagesources{$page};
411                 $type=pagetype($file);
412         }
413         else {
414                 $type=$form->param('type');
415                 if (defined $type && length $type && $hooks{htmlize}{$type}) {
416                         $type=possibly_foolish_untaint($type);
417                 }
418                 elsif (defined $from) {
419                         # favor the type of linking page
420                         $type=pagetype($pagesources{$from});
421                 }
422                 $type=$config{default_pageext} unless defined $type;
423                 $file=$page.".".$type;
424         }
425
426         my $newfile=0;
427         if (! -e "$config{srcdir}/$file") {
428                 $newfile=1;
429         }
430
431         $form->field(name => "do", type => 'hidden');
432         $form->field(name => "from", type => 'hidden');
433         $form->field(name => "rcsinfo", type => 'hidden');
434         $form->field(name => "subpage", type => 'hidden');
435         $form->field(name => "page", value => $page, force => 1);
436         $form->field(name => "type", value => $type, force => 1);
437         $form->field(name => "comments", type => "text", size => 80);
438         $form->field(name => "editcontent", type => "textarea", rows => 20,
439                 cols => 80);
440         $form->tmpl_param("can_commit", $config{rcs});
441         $form->tmpl_param("indexlink", indexlink());
442         $form->tmpl_param("helponformattinglink",
443                 htmllink("", "", "HelpOnFormatting", 1));
444         $form->tmpl_param("baseurl", baseurl());
445         if (! $form->submitted) {
446                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
447                         force => 1);
448         }
449         
450         if ($form->submitted eq "Cancel") {
451                 if ($newfile && defined $from) {
452                         redirect($q, "$config{url}/".htmlpage($from));
453                 }
454                 elsif ($newfile) {
455                         redirect($q, $config{url});
456                 }
457                 else {
458                         redirect($q, "$config{url}/".htmlpage($page));
459                 }
460                 return;
461         }
462         elsif ($form->submitted eq "Preview") {
463                 my $content=$form->field('editcontent');
464                 my $comments=$form->field('comments');
465                 $form->field(name => "editcontent",
466                                 value => $content, force => 1);
467                 $form->field(name => "comments",
468                                 value => $comments, force => 1);
469                 $config{rss}=$config{atom}=0; # avoid preview writing a feed!
470                 $form->tmpl_param("page_preview",
471                         htmlize($page, $type,
472                         linkify($page, "",
473                         preprocess($page, $page,
474                         filter($page, $content)))));
475         }
476         else {
477                 $form->tmpl_param("page_preview", "");
478         }
479         $form->tmpl_param("page_conflict", "");
480         
481         if (! $form->submitted || $form->submitted eq "Preview" || 
482             ! $form->validate) {
483                 if ($form->field("do") eq "create") {
484                         my @page_locs;
485                         my $best_loc;
486                         if (! defined $from || ! length $from ||
487                             $from ne $form->field('from') ||
488                             $from=~/$config{wiki_file_prune_regexp}/ ||
489                             $from=~/^\// ||
490                             $form->submitted eq "Preview") {
491                                 @page_locs=$best_loc=$page;
492                         }
493                         else {
494                                 my $dir=$from."/";
495                                 $dir=~s![^/]+/+$!!;
496                                 
497                                 if ((defined $form->field('subpage') && length $form->field('subpage')) ||
498                                     $page eq 'discussion') {
499                                         $best_loc="$from/$page";
500                                 }
501                                 else {
502                                         $best_loc=$dir.$page;
503                                 }
504                                 
505                                 push @page_locs, $dir.$page;
506                                 push @page_locs, "$from/$page";
507                                 while (length $dir) {
508                                         $dir=~s![^/]+/+$!!;
509                                         push @page_locs, $dir.$page;
510                                 }
511                         }
512
513                         @page_locs = grep {
514                                 ! exists $pagecase{lc $_} &&
515                                 ! page_locked($_, $session, 1)
516                         } @page_locs;
517                         
518                         if (! @page_locs) {
519                                 # hmm, someone else made the page in the
520                                 # meantime?
521                                 redirect($q, "$config{url}/".htmlpage($page));
522                                 return;
523                         }
524                         
525                         my @page_types;
526                         if (exists $hooks{htmlize}) {
527                                 @page_types=keys %{$hooks{htmlize}};
528                         }
529                         
530                         $form->tmpl_param("page_select", 1);
531                         $form->field(name => "page", type => 'select',
532                                 options => \@page_locs, value => $best_loc);
533                         $form->field(name => "type", type => 'select',
534                                 options => \@page_types);
535                         $form->title("creating ".pagetitle($page));
536                 }
537                 elsif ($form->field("do") eq "edit") {
538                         page_locked($page, $session);
539                         if (! defined $form->field('editcontent') || 
540                             ! length $form->field('editcontent')) {
541                                 my $content="";
542                                 if (exists $pagesources{$page}) {
543                                         $content=readfile(srcfile($pagesources{$page}));
544                                         $content=~s/\n/\r\n/g;
545                                 }
546                                 $form->field(name => "editcontent", value => $content,
547                                         force => 1);
548                         }
549                         $form->tmpl_param("page_select", 0);
550                         $form->field(name => "page", type => 'hidden');
551                         $form->field(name => "type", type => 'hidden');
552                         $form->title("editing ".pagetitle($page));
553                 }
554                 
555                 print $form->render(submit => \@buttons);
556         }
557         else {
558                 # save page
559                 page_locked($page, $session);
560                 
561                 my $content=$form->field('editcontent');
562
563                 $content=~s/\r\n/\n/g;
564                 $content=~s/\r/\n/g;
565                 writefile($file, $config{srcdir}, $content);
566                 
567                 my $message="web commit ";
568                 if (defined $session->param("name") && 
569                     length $session->param("name")) {
570                         $message.="by ".$session->param("name");
571                 }
572                 else {
573                         $message.="from $ENV{REMOTE_ADDR}";
574                 }
575                 if (defined $form->field('comments') &&
576                     length $form->field('comments')) {
577                         $message.=": ".$form->field('comments');
578                 }
579                 
580                 if ($config{rcs}) {
581                         if ($newfile) {
582                                 rcs_add($file);
583                         }
584                         # prevent deadlock with post-commit hook
585                         unlockwiki();
586                         # presumably the commit will trigger an update
587                         # of the wiki
588                         my $conflict=rcs_commit($file, $message,
589                                 $form->field("rcsinfo"));
590                 
591                         if (defined $conflict) {
592                                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
593                                         force => 1);
594                                 $form->tmpl_param("page_conflict", 1);
595                                 $form->field("editcontent", value => $conflict, force => 1);
596                                 $form->field(name => "comments", value => $form->field('comments'), force => 1);
597                                 $form->field("do", "edit)");
598                                 $form->tmpl_param("page_select", 0);
599                                 $form->field(name => "page", type => 'hidden');
600                                 $form->field(name => "type", type => 'hidden');
601                                 $form->title("editing $page");
602                                 print $form->render(submit => \@buttons);
603                                 return;
604                         }
605                 }
606                 else {
607                         require IkiWiki::Render;
608                         refresh();
609                         saveindex();
610                 }
611                 
612                 # The trailing question mark tries to avoid broken
613                 # caches and get the most recent version of the page.
614                 redirect($q, "$config{url}/".htmlpage($page)."?updated");
615         }
616 } #}}}
617
618 sub cgi () { #{{{
619         eval q{use CGI};
620         eval q{use CGI::Session};
621         
622         my $q=CGI->new;
623         
624         run_hooks(cgi => sub { shift->($q) });
625         
626         my $do=$q->param('do');
627         if (! defined $do || ! length $do) {
628                 my $error = $q->cgi_error;
629                 if ($error) {
630                         error("Request not processed: $error");
631                 }
632                 else {
633                         error("\"do\" parameter missing");
634                 }
635         }
636         
637         # Things that do not need a session.
638         if ($do eq 'recentchanges') {
639                 cgi_recentchanges($q);
640                 return;
641         }
642         elsif ($do eq 'hyperestraier') {
643                 cgi_hyperestraier();
644         }
645         
646         CGI::Session->name("ikiwiki_session_".encode_utf8($config{wikiname}));
647         
648         my $oldmask=umask(077);
649         my $session = CGI::Session->new("driver:DB_File", $q,
650                 { FileName => "$config{wikistatedir}/sessions.db" });
651         umask($oldmask);
652         
653         # Everything below this point needs the user to be signed in.
654         if (((! $config{anonok} || $do eq 'prefs') &&
655              (! $config{httpauth}) &&
656              (! defined $session->param("name") ||
657              ! userinfo_get($session->param("name"), "regdate"))) || $do eq 'signin') {
658                 cgi_signin($q, $session);
659         
660                 # Force session flush with safe umask.
661                 my $oldmask=umask(077);
662                 $session->flush;
663                 umask($oldmask);
664                 
665                 return;
666         }
667
668         if ($config{httpauth} && (! defined $session->param("name"))) {
669                 if (! defined $q->remote_user()) {
670                         error("Could not determine authenticated username.");
671                 }
672                 else {
673                         $session->param("name", $q->remote_user());
674                         if (!userinfo_get($session->param("name"),"regdate")) {
675                                 userinfo_setall($session->param("name"), {
676                                         email => "",
677                                         password => "",
678                                         regdate=>time,
679                                 });
680                         }
681                 }
682         }
683         
684         if ($do eq 'create' || $do eq 'edit') {
685                 cgi_editpage($q, $session);
686         }
687         elsif ($do eq 'prefs') {
688                 cgi_prefs($q, $session);
689         }
690         elsif ($do eq 'blog') {
691                 my $page=titlepage(decode_utf8($q->param('title')));
692                 # if the page already exists, munge it to be unique
693                 my $from=$q->param('from');
694                 my $add="";
695                 while (exists $pagecase{lc "$from/$page$add"}) {
696                         $add=1 unless length $add;
697                         $add++;
698                 }
699                 $q->param('page', $page.$add);
700                 # now run same as create
701                 $q->param('do', 'create');
702                 cgi_editpage($q, $session);
703         }
704         else {
705                 error("unknown do parameter");
706         }
707 } #}}}
708
709 1