fix data:image handling
[ikiwiki.git] / IkiWiki / CGI.pm
blob1e0ee01eb0a0129230b72fb7bd5111c35e5c9873
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;
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');
22 } #}}}
24 sub redirect ($$) { #{{{
25 my $q=shift;
26 my $url=shift;
27 if (! $config{w3mmode}) {
28 print $q->redirect($url);
30 else {
31 print "Content-type: text/plain\n";
32 print "W3m-control: GOTO $url\n\n";
34 } #}}}
36 sub page_locked ($$;$) { #{{{
37 my $page=shift;
38 my $session=shift;
39 my $nonfatal=shift;
41 my $user=$session->param("name");
42 return if defined $user && is_admin($user);
44 foreach my $admin (@{$config{adminuser}}) {
45 my $locked_pages=userinfo_get($admin, "locked_pages");
46 if (pagespec_match($page, userinfo_get($admin, "locked_pages"))) {
47 return 1 if $nonfatal;
48 error(htmllink("", "", $page, 1)." is locked by ".
49 htmllink("", "", $admin, 1)." and cannot be edited.");
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,
65 } #}}}
67 sub cgi_recentchanges ($) { #{{{
68 my $q=shift;
70 unlockwiki();
72 # Optimisation: building recentchanges means calculating lots of
73 # links. Memoizing htmllink speeds it up a lot (can't be memoized
74 # during page builds as the return values may change, but they
75 # won't here.)
76 eval q{use Memoize};
77 error($@) if $@;
78 memoize("htmllink");
80 eval q{use Time::Duration};
81 error($@) if $@;
82 eval q{use CGI 'escapeHTML'};
83 error($@) if $@;
85 my $changelog=[rcs_recentchanges(100)];
86 foreach my $change (@$changelog) {
87 $change->{when} = concise(ago($change->{when}));
88 $change->{user} = htmllink("", "", escapeHTML($change->{user}), 1);
90 my $is_excess = exists $change->{pages}[10]; # limit pages to first 10
91 delete @{$change->{pages}}[10 .. @{$change->{pages}}] if $is_excess;
92 $change->{pages} = [
93 map {
94 $_->{link} = htmllink("", "", $_->{page}, 1);
95 $_;
96 } @{$change->{pages}}
98 push @{$change->{pages}}, { link => '...' } if $is_excess;
101 my $template=template("recentchanges.tmpl");
102 $template->param(
103 title => "RecentChanges",
104 indexlink => indexlink(),
105 wikiname => $config{wikiname},
106 changelog => $changelog,
107 baseurl => baseurl(),
109 run_hooks(pagetemplate => sub {
110 shift->(page => "", destpage => "", template => $template);
112 print $q->header(-charset => 'utf-8'), $template->output;
113 } #}}}
115 sub cgi_signin ($$) { #{{{
116 my $q=shift;
117 my $session=shift;
119 eval q{use CGI::FormBuilder};
120 error($@) if $@;
121 my $form = CGI::FormBuilder->new(
122 title => "signin",
123 fields => [qw(do title page subpage from name password)],
124 header => 1,
125 charset => "utf-8",
126 method => 'POST',
127 validate => {
128 confirm_password => {
129 perl => q{eq $form->field("password")},
131 email => 'EMAIL',
133 required => 'NONE',
134 javascript => 0,
135 params => $q,
136 action => $config{cgiurl},
137 header => 0,
138 template => (-e "$config{templatedir}/signin.tmpl" ?
139 {template_params("signin.tmpl")} : ""),
140 stylesheet => baseurl()."style.css",
143 decode_form_utf8($form);
145 $form->field(name => "name", required => 0);
146 $form->field(name => "do", type => "hidden");
147 $form->field(name => "page", type => "hidden");
148 $form->field(name => "title", type => "hidden");
149 $form->field(name => "from", type => "hidden");
150 $form->field(name => "subpage", type => "hidden");
151 $form->field(name => "password", type => "password", required => 0);
152 if ($form->submitted eq "Register" || $form->submitted eq "Create Account") {
153 $form->title("register");
154 $form->text("");
155 $form->fields(qw(do title page subpage from name password confirm_password email));
156 $form->field(name => "confirm_password", type => "password");
157 $form->field(name => "email", type => "text");
159 if ($q->param("do") ne "signin" && !$form->submitted) {
160 $form->text("You need to log in first.");
163 if ($form->submitted) {
164 # Set required fields based on how form was submitted.
165 my %required=(
166 "Login" => [qw(name password)],
167 "Register" => [],
168 "Create Account" => [qw(name password confirm_password email)],
169 "Mail Password" => [qw(name)],
171 foreach my $opt (@{$required{$form->submitted}}) {
172 $form->field(name => $opt, required => 1);
175 # Validate password differently depending on how
176 # form was submitted.
177 if ($form->submitted eq 'Login') {
178 $form->field(
179 name => "password",
180 validate => sub {
181 length $form->field("name") &&
182 shift eq userinfo_get($form->field("name"), 'password');
185 $form->field(name => "name", validate => '/^\w+$/');
187 else {
188 $form->field(name => "password", validate => 'VALUE');
190 # And make sure the entered name exists when logging
191 # in or sending email, and does not when registering.
192 if ($form->submitted eq 'Create Account' ||
193 $form->submitted eq 'Register') {
194 $form->field(
195 name => "name",
196 validate => sub {
197 my $name=shift;
198 length $name &&
199 $name=~/$config{wiki_file_regexp}/ &&
200 ! userinfo_get($name, "regdate");
204 else {
205 $form->field(
206 name => "name",
207 validate => sub {
208 my $name=shift;
209 length $name &&
210 userinfo_get($name, "regdate");
215 else {
216 # First time settings.
217 $form->field(name => "name", comment => "use FirstnameLastName");
218 if ($session->param("name")) {
219 $form->field(name => "name", value => $session->param("name"));
223 if ($form->submitted && $form->validate) {
224 if ($form->submitted eq 'Login') {
225 $session->param("name", $form->field("name"));
226 if (defined $form->field("do") &&
227 $form->field("do") ne 'signin') {
228 redirect($q, cgiurl(
229 do => $form->field("do"),
230 page => $form->field("page"),
231 title => $form->field("title"),
232 subpage => $form->field("subpage"),
233 from => $form->field("from"),
236 else {
237 redirect($q, $config{url});
240 elsif ($form->submitted eq 'Create Account') {
241 my $user_name=$form->field('name');
242 if (userinfo_setall($user_name, {
243 'email' => $form->field('email'),
244 'password' => $form->field('password'),
245 'regdate' => time
246 })) {
247 $form->field(name => "confirm_password", type => "hidden");
248 $form->field(name => "email", type => "hidden");
249 $form->text("Account creation successful. Now you can Login.");
250 printheader($session);
251 print misctemplate($form->title, $form->render(submit => ["Login"]));
253 else {
254 error("Error creating account.");
257 elsif ($form->submitted eq 'Mail Password') {
258 my $user_name=$form->field("name");
259 my $template=template("passwordmail.tmpl");
260 $template->param(
261 user_name => $user_name,
262 user_password => userinfo_get($user_name, "password"),
263 wikiurl => $config{url},
264 wikiname => $config{wikiname},
265 REMOTE_ADDR => $ENV{REMOTE_ADDR},
268 eval q{use Mail::Sendmail};
269 error($@) if $@;
270 sendmail(
271 To => userinfo_get($user_name, "email"),
272 From => "$config{wikiname} admin <$config{adminemail}>",
273 Subject => "$config{wikiname} information",
274 Message => $template->output,
275 ) or error("Failed to send mail");
277 $form->text("Your password has been emailed to you.");
278 $form->field(name => "name", required => 0);
279 printheader($session);
280 print misctemplate($form->title, $form->render(submit => ["Login", "Mail Password"]));
282 elsif ($form->submitted eq "Register") {
283 printheader($session);
284 print misctemplate($form->title, $form->render(submit => ["Create Account"]));
287 elsif ($form->submitted eq "Create Account") {
288 printheader($session);
289 print misctemplate($form->title, $form->render(submit => ["Create Account"]));
291 else {
292 printheader($session);
293 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
295 } #}}}
297 sub cgi_prefs ($$) { #{{{
298 my $q=shift;
299 my $session=shift;
301 eval q{use CGI::FormBuilder};
302 error($@) if $@;
303 my $form = CGI::FormBuilder->new(
304 title => "preferences",
305 fields => [qw(do name password confirm_password email
306 subscriptions locked_pages)],
307 header => 0,
308 charset => "utf-8",
309 method => 'POST',
310 validate => {
311 confirm_password => {
312 perl => q{eq $form->field("password")},
314 email => 'EMAIL',
316 required => 'NONE',
317 javascript => 0,
318 params => $q,
319 action => $config{cgiurl},
320 template => (-e "$config{templatedir}/prefs.tmpl" ?
321 {template_params("prefs.tmpl")} : ""),
322 stylesheet => baseurl()."style.css",
324 my @buttons=("Save Preferences", "Logout", "Cancel");
326 my $user_name=$session->param("name");
327 $form->field(name => "do", type => "hidden");
328 $form->field(name => "name", disabled => 1,
329 value => $user_name, force => 1);
330 $form->field(name => "password", type => "password");
331 $form->field(name => "confirm_password", type => "password");
332 $form->field(name => "subscriptions", size => 50,
333 comment => "(".htmllink("", "", "PageSpec", 1).")");
334 $form->field(name => "locked_pages", size => 50,
335 comment => "(".htmllink("", "", "PageSpec", 1).")");
336 $form->field(name => "banned_users", size => 50);
338 if (! is_admin($user_name)) {
339 $form->field(name => "locked_pages", type => "hidden");
340 $form->field(name => "banned_users", type => "hidden");
343 if ($config{httpauth}) {
344 $form->field(name => "password", type => "hidden");
345 $form->field(name => "confirm_password", type => "hidden");
348 if (! $form->submitted) {
349 $form->field(name => "email", force => 1,
350 value => userinfo_get($user_name, "email"));
351 $form->field(name => "subscriptions", force => 1,
352 value => userinfo_get($user_name, "subscriptions"));
353 $form->field(name => "locked_pages", force => 1,
354 value => userinfo_get($user_name, "locked_pages"));
355 if (is_admin($user_name)) {
356 $form->field(name => "banned_users", force => 1,
357 value => join(" ", get_banned_users()));
361 decode_form_utf8($form);
363 if ($form->submitted eq 'Logout') {
364 $session->delete();
365 redirect($q, $config{url});
366 return;
368 elsif ($form->submitted eq 'Cancel') {
369 redirect($q, $config{url});
370 return;
372 elsif ($form->submitted eq "Save Preferences" && $form->validate) {
373 foreach my $field (qw(password email subscriptions locked_pages)) {
374 if (length $form->field($field)) {
375 userinfo_set($user_name, $field, $form->field($field)) || error("failed to set $field");
378 if (is_admin($user_name)) {
379 set_banned_users(grep { ! is_admin($_) }
380 split(' ', $form->field("banned_users")));
382 $form->text("Preferences saved.");
385 printheader($session);
386 print misctemplate($form->title, $form->render(submit => \@buttons));
387 } #}}}
389 sub cgi_editpage ($$) { #{{{
390 my $q=shift;
391 my $session=shift;
393 my @fields=qw(do rcsinfo subpage from page type editcontent comments);
394 my @buttons=("Save Page", "Preview", "Cancel");
396 eval q{use CGI::FormBuilder; use CGI::FormBuilder::Template::HTML};
397 error($@) if $@;
398 my $renderer=CGI::FormBuilder::Template::HTML->new(
399 fields => \@fields,
400 template_params("editpage.tmpl"),
402 run_hooks(pagetemplate => sub {
403 shift->(page => "", destpage => "", template => $renderer->engine);
405 my $form = CGI::FormBuilder->new(
406 fields => \@fields,
407 header => 1,
408 charset => "utf-8",
409 method => 'POST',
410 validate => {
411 editcontent => '/.+/',
413 required => [qw{editcontent}],
414 javascript => 0,
415 params => $q,
416 action => $config{cgiurl},
417 table => 0,
418 template => $renderer,
421 decode_form_utf8($form);
423 # This untaint is safe because titlepage removes any problematic
424 # characters.
425 my ($page)=$form->field('page');
426 $page=titlepage(possibly_foolish_untaint($page));
427 if (! defined $page || ! length $page ||
428 $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
429 error("bad page name");
432 my $from;
433 if (defined $form->field('from')) {
434 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
437 my $file;
438 my $type;
439 if (exists $pagesources{$page}) {
440 $file=$pagesources{$page};
441 $type=pagetype($file);
442 if (! defined $type) {
443 error("$page is not an editable page");
446 else {
447 $type=$form->param('type');
448 if (defined $type && length $type && $hooks{htmlize}{$type}) {
449 $type=possibly_foolish_untaint($type);
451 elsif (defined $from) {
452 # favor the type of linking page
453 $type=pagetype($pagesources{$from});
455 $type=$config{default_pageext} unless defined $type;
456 $file=$page.".".$type;
459 my $newfile=0;
460 if (! -e "$config{srcdir}/$file") {
461 $newfile=1;
464 $form->field(name => "do", type => 'hidden');
465 $form->field(name => "from", type => 'hidden');
466 $form->field(name => "rcsinfo", type => 'hidden');
467 $form->field(name => "subpage", type => 'hidden');
468 $form->field(name => "page", value => $page, force => 1);
469 $form->field(name => "type", value => $type, force => 1);
470 $form->field(name => "comments", type => "text", size => 80);
471 $form->field(name => "editcontent", type => "textarea", rows => 20,
472 cols => 80);
473 $form->tmpl_param("can_commit", $config{rcs});
474 $form->tmpl_param("indexlink", indexlink());
475 $form->tmpl_param("helponformattinglink",
476 htmllink("", "", "HelpOnFormatting", 1));
477 $form->tmpl_param("baseurl", baseurl());
478 if (! $form->submitted) {
479 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
480 force => 1);
483 if ($form->submitted eq "Cancel") {
484 if ($newfile && defined $from) {
485 redirect($q, "$config{url}/".htmlpage($from));
487 elsif ($newfile) {
488 redirect($q, $config{url});
490 else {
491 redirect($q, "$config{url}/".htmlpage($page));
493 return;
495 elsif ($form->submitted eq "Preview") {
496 my $content=$form->field('editcontent');
497 my $comments=$form->field('comments');
498 $form->field(name => "editcontent",
499 value => $content, force => 1);
500 $form->field(name => "comments",
501 value => $comments, force => 1);
502 $config{rss}=$config{atom}=0; # avoid preview writing a feed!
503 $form->tmpl_param("page_preview",
504 htmlize($page, $type,
505 linkify($page, "",
506 preprocess($page, $page,
507 filter($page, $content)))));
509 else {
510 $form->tmpl_param("page_preview", "");
512 $form->tmpl_param("page_conflict", "");
514 if (! $form->submitted || $form->submitted eq "Preview" ||
515 ! $form->validate) {
516 if ($form->field("do") eq "create") {
517 my @page_locs;
518 my $best_loc;
519 if (! defined $from || ! length $from ||
520 $from ne $form->field('from') ||
521 $from=~/$config{wiki_file_prune_regexp}/ ||
522 $from=~/^\// ||
523 $form->submitted eq "Preview") {
524 @page_locs=$best_loc=$page;
526 else {
527 my $dir=$from."/";
528 $dir=~s![^/]+/+$!!;
530 if ((defined $form->field('subpage') && length $form->field('subpage')) ||
531 $page eq 'discussion') {
532 $best_loc="$from/$page";
534 else {
535 $best_loc=$dir.$page;
538 push @page_locs, $dir.$page;
539 push @page_locs, "$from/$page";
540 while (length $dir) {
541 $dir=~s![^/]+/+$!!;
542 push @page_locs, $dir.$page;
546 @page_locs = grep {
547 ! exists $pagecase{lc $_} &&
548 ! page_locked($_, $session, 1)
549 } @page_locs;
551 if (! @page_locs) {
552 # hmm, someone else made the page in the
553 # meantime?
554 redirect($q, "$config{url}/".htmlpage($page));
555 return;
558 my @page_types;
559 if (exists $hooks{htmlize}) {
560 @page_types=keys %{$hooks{htmlize}};
563 $form->tmpl_param("page_select", 1);
564 $form->field(name => "page", type => 'select',
565 options => \@page_locs, value => $best_loc);
566 $form->field(name => "type", type => 'select',
567 options => \@page_types);
568 $form->title("creating ".pagetitle($page));
570 elsif ($form->field("do") eq "edit") {
571 page_locked($page, $session);
572 if (! defined $form->field('editcontent') ||
573 ! length $form->field('editcontent')) {
574 my $content="";
575 if (exists $pagesources{$page}) {
576 $content=readfile(srcfile($pagesources{$page}));
577 $content=~s/\n/\r\n/g;
579 $form->field(name => "editcontent", value => $content,
580 force => 1);
582 $form->tmpl_param("page_select", 0);
583 $form->field(name => "page", type => 'hidden');
584 $form->field(name => "type", type => 'hidden');
585 $form->title("editing ".pagetitle($page));
588 print $form->render(submit => \@buttons);
590 else {
591 # save page
592 page_locked($page, $session);
594 my $content=$form->field('editcontent');
596 $content=~s/\r\n/\n/g;
597 $content=~s/\r/\n/g;
598 writefile($file, $config{srcdir}, $content);
600 my $message="web commit ";
601 if (defined $session->param("name") &&
602 length $session->param("name")) {
603 $message.="by ".$session->param("name");
605 else {
606 $message.="from $ENV{REMOTE_ADDR}";
608 if (defined $form->field('comments') &&
609 length $form->field('comments')) {
610 $message.=": ".$form->field('comments');
613 if ($config{rcs}) {
614 if ($newfile) {
615 rcs_add($file);
617 # prevent deadlock with post-commit hook
618 unlockwiki();
619 # presumably the commit will trigger an update
620 # of the wiki
621 my $conflict=rcs_commit($file, $message,
622 $form->field("rcsinfo"));
624 if (defined $conflict) {
625 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
626 force => 1);
627 $form->tmpl_param("page_conflict", 1);
628 $form->field("editcontent", value => $conflict, force => 1);
629 $form->field(name => "comments", value => $form->field('comments'), force => 1);
630 $form->field("do", "edit)");
631 $form->tmpl_param("page_select", 0);
632 $form->field(name => "page", type => 'hidden');
633 $form->field(name => "type", type => 'hidden');
634 $form->title("editing $page");
635 print $form->render(submit => \@buttons);
636 return;
639 else {
640 require IkiWiki::Render;
641 refresh();
642 saveindex();
645 # The trailing question mark tries to avoid broken
646 # caches and get the most recent version of the page.
647 redirect($q, "$config{url}/".htmlpage($page)."?updated");
649 } #}}}
651 sub cgi () { #{{{
652 eval q{use CGI; use CGI::Session};
653 error($@) if $@;
655 my $q=CGI->new;
657 run_hooks(cgi => sub { shift->($q) });
659 my $do=$q->param('do');
660 if (! defined $do || ! length $do) {
661 my $error = $q->cgi_error;
662 if ($error) {
663 error("Request not processed: $error");
665 else {
666 error("\"do\" parameter missing");
670 # Things that do not need a session.
671 if ($do eq 'recentchanges') {
672 cgi_recentchanges($q);
673 return;
675 elsif ($do eq 'hyperestraier') {
676 cgi_hyperestraier();
679 CGI::Session->name("ikiwiki_session_".encode_utf8($config{wikiname}));
681 my $oldmask=umask(077);
682 my $session = CGI::Session->new("driver:DB_File", $q,
683 { FileName => "$config{wikistatedir}/sessions.db" });
684 umask($oldmask);
686 # Everything below this point needs the user to be signed in.
687 if (((! $config{anonok} || $do eq 'prefs') &&
688 (! $config{httpauth}) &&
689 (! defined $session->param("name") ||
690 ! userinfo_get($session->param("name"), "regdate"))) || $do eq 'signin') {
691 cgi_signin($q, $session);
693 # Force session flush with safe umask.
694 my $oldmask=umask(077);
695 $session->flush;
696 umask($oldmask);
698 return;
701 if ($config{httpauth} && (! defined $session->param("name"))) {
702 if (! defined $q->remote_user()) {
703 error("Could not determine authenticated username.");
705 else {
706 $session->param("name", $q->remote_user());
707 if (! userinfo_get($session->param("name"), "regdate")) {
708 userinfo_setall($session->param("name"), {
709 email => "",
710 password => "",
711 regdate=>time,
717 if (defined $session->param("name") && userinfo_get($session->param("name"), "banned")) {
718 print $q->header(-status => "403 Forbidden");
719 $session->delete();
720 print "You are banned.";
721 exit;
724 if ($do eq 'create' || $do eq 'edit') {
725 cgi_editpage($q, $session);
727 elsif ($do eq 'prefs') {
728 cgi_prefs($q, $session);
730 elsif ($do eq 'blog') {
731 my $page=titlepage(decode_utf8($q->param('title')));
732 # if the page already exists, munge it to be unique
733 my $from=$q->param('from');
734 my $add="";
735 while (exists $pagecase{lc "$from/$page$add"}) {
736 $add=1 unless length $add;
737 $add++;
739 $q->param('page', $page.$add);
740 # now run same as create
741 $q->param('do', 'create');
742 cgi_editpage($q, $session);
744 else {
745 error("unknown do parameter");
747 } #}}}