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