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