web commit by WillThompson: Safety of arbitrary regexen
[ikiwiki.git] / IkiWiki / CGI.pm
1 #!/usr/bin/perl
2
3 use warnings;
4 use strict;
5
6 package IkiWiki;
7
8 sub page_locked ($$;$) { #{{{
9         my $page=shift;
10         my $session=shift;
11         my $nonfatal=shift;
12         
13         my $user=$session->param("name");
14         return if length $user && is_admin($user);
15
16         foreach my $admin (@{$config{adminuser}}) {
17                 my $locked_pages=userinfo_get($admin, "locked_pages");
18                 if (globlist_match($page, userinfo_get($admin, "locked_pages"))) {
19                         return 1 if $nonfatal;
20                         error(htmllink("", $page, 1)." is locked by ".
21                               htmllink("", $admin, 1)." and cannot be edited.");
22                 }
23         }
24
25         return 0;
26 } #}}}
27
28 sub cgi_recentchanges ($) { #{{{
29         my $q=shift;
30         
31         unlockwiki();
32
33         my $template=HTML::Template->new(
34                 filename => "$config{templatedir}/recentchanges.tmpl"
35         );
36         $template->param(
37                 title => "RecentChanges",
38                 indexlink => indexlink(),
39                 wikiname => $config{wikiname},
40                 changelog => [rcs_recentchanges(100)],
41                 styleurl => styleurl(),
42                 baseurl => "$config{url}/",
43         );
44         print $q->header, $template->output;
45 } #}}}
46
47 sub cgi_signin ($$) { #{{{
48         my $q=shift;
49         my $session=shift;
50
51         eval q{use CGI::FormBuilder};
52         my $form = CGI::FormBuilder->new(
53                 title => "signin",
54                 fields => [qw(do title page subpage from name password confirm_password email)],
55                 header => 1,
56                 method => 'POST',
57                 validate => {
58                         confirm_password => {
59                                 perl => q{eq $form->field("password")},
60                         },
61                         email => 'EMAIL',
62                 },
63                 required => 'NONE',
64                 javascript => 0,
65                 params => $q,
66                 # Why was this added?
67                 #action => $q->request_uri,
68                 header => 0,
69                 template => (-e "$config{templatedir}/signin.tmpl" ?
70                               "$config{templatedir}/signin.tmpl" : ""),
71                 stylesheet => styleurl(),
72         );
73         
74         $form->field(name => "name", required => 0);
75         $form->field(name => "do", type => "hidden");
76         $form->field(name => "page", type => "hidden");
77         $form->field(name => "title", type => "hidden");
78         $form->field(name => "from", type => "hidden");
79         $form->field(name => "subpage", type => "hidden");
80         $form->field(name => "password", type => "password", required => 0);
81         $form->field(name => "confirm_password", type => "password", required => 0);
82         $form->field(name => "email", required => 0);
83         if ($q->param("do") ne "signin") {
84                 $form->text("You need to log in first.");
85         }
86         
87         if ($form->submitted) {
88                 # Set required fields based on how form was submitted.
89                 my %required=(
90                         "Login" => [qw(name password)],
91                         "Register" => [qw(name password confirm_password email)],
92                         "Mail Password" => [qw(name)],
93                 );
94                 foreach my $opt (@{$required{$form->submitted}}) {
95                         $form->field(name => $opt, required => 1);
96                 }
97         
98                 # Validate password differently depending on how
99                 # form was submitted.
100                 if ($form->submitted eq 'Login') {
101                         $form->field(
102                                 name => "password",
103                                 validate => sub {
104                                         length $form->field("name") &&
105                                         shift eq userinfo_get($form->field("name"), 'password');
106                                 },
107                         );
108                         $form->field(name => "name", validate => '/^\w+$/');
109                 }
110                 else {
111                         $form->field(name => "password", validate => 'VALUE');
112                 }
113                 # And make sure the entered name exists when logging
114                 # in or sending email, and does not when registering.
115                 if ($form->submitted eq 'Register') {
116                         $form->field(
117                                 name => "name",
118                                 validate => sub {
119                                         my $name=shift;
120                                         length $name &&
121                                         ! userinfo_get($name, "regdate");
122                                 },
123                         );
124                 }
125                 else {
126                         $form->field(
127                                 name => "name",
128                                 validate => sub {
129                                         my $name=shift;
130                                         length $name &&
131                                         userinfo_get($name, "regdate");
132                                 },
133                         );
134                 }
135         }
136         else {
137                 # First time settings.
138                 $form->field(name => "name", comment => "use FirstnameLastName");
139                 $form->field(name => "confirm_password", comment => "(only needed");
140                 $form->field(name => "email",            comment => "for registration)");
141                 if ($session->param("name")) {
142                         $form->field(name => "name", value => $session->param("name"));
143                 }
144         }
145
146         if ($form->submitted && $form->validate) {
147                 if ($form->submitted eq 'Login') {
148                         $session->param("name", $form->field("name"));
149                         if (defined $form->field("do") && 
150                             $form->field("do") ne 'signin') {
151                                 print $q->redirect(cgiurl(
152                                         do => $form->field("do"),
153                                         page => $form->field("page"),
154                                         title => $form->field("title"),
155                                         subpage => $form->field("subpage"),
156                                         from => $form->field("from"),
157                                 ));
158                         }
159                         else {
160                                 print $q->redirect($config{url});
161                         }
162                 }
163                 elsif ($form->submitted eq 'Register') {
164                         my $user_name=$form->field('name');
165                         if (userinfo_setall($user_name, {
166                                            'email' => $form->field('email'),
167                                            'password' => $form->field('password'),
168                                            'regdate' => time
169                                          })) {
170                                 $form->field(name => "confirm_password", type => "hidden");
171                                 $form->field(name => "email", type => "hidden");
172                                 $form->text("Registration successful. Now you can Login.");
173                                 print $session->header();
174                                 print misctemplate($form->title, $form->render(submit => ["Login"]));
175                         }
176                         else {
177                                 error("Error saving registration.");
178                         }
179                 }
180                 elsif ($form->submitted eq 'Mail Password') {
181                         my $user_name=$form->field("name");
182                         my $template=HTML::Template->new(
183                                 filename => "$config{templatedir}/passwordmail.tmpl"
184                         );
185                         $template->param(
186                                 user_name => $user_name,
187                                 user_password => userinfo_get($user_name, "password"),
188                                 wikiurl => $config{url},
189                                 wikiname => $config{wikiname},
190                                 REMOTE_ADDR => $ENV{REMOTE_ADDR},
191                         );
192                         
193                         eval q{use Mail::Sendmail};
194                         my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
195                         sendmail(
196                                 To => userinfo_get($user_name, "email"),
197                                 From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
198                                 Subject => "$config{wikiname} information",
199                                 Message => $template->output,
200                         ) or error("Failed to send mail");
201                         
202                         $form->text("Your password has been emailed to you.");
203                         $form->field(name => "name", required => 0);
204                         print $session->header();
205                         print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
206                 }
207         }
208         else {
209                 print $session->header();
210                 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
211         }
212 } #}}}
213
214 sub cgi_prefs ($$) { #{{{
215         my $q=shift;
216         my $session=shift;
217
218         eval q{use CGI::FormBuilder};
219         my $form = CGI::FormBuilder->new(
220                 title => "preferences",
221                 fields => [qw(do name password confirm_password email locked_pages)],
222                 header => 0,
223                 method => 'POST',
224                 validate => {
225                         confirm_password => {
226                                 perl => q{eq $form->field("password")},
227                         },
228                         email => 'EMAIL',
229                 },
230                 required => 'NONE',
231                 javascript => 0,
232                 params => $q,
233                 action => $q->request_uri,
234                 template => (-e "$config{templatedir}/prefs.tmpl" ?
235                               "$config{templatedir}/prefs.tmpl" : ""),
236                 stylesheet => styleurl(),
237         );
238         my @buttons=("Save Preferences", "Logout", "Cancel");
239         
240         my $user_name=$session->param("name");
241         $form->field(name => "do", type => "hidden");
242         $form->field(name => "name", disabled => 1,
243                 value => $user_name, force => 1);
244         $form->field(name => "password", type => "password");
245         $form->field(name => "confirm_password", type => "password");
246         $form->field(name => "locked_pages", size => 50,
247                 comment => "(".htmllink("", "GlobList", 1).")");
248         
249         if (! is_admin($user_name)) {
250                 $form->field(name => "locked_pages", type => "hidden");
251         }
252         
253         if (! $form->submitted) {
254                 $form->field(name => "email", force => 1,
255                         value => userinfo_get($user_name, "email"));
256                 $form->field(name => "locked_pages", force => 1,
257                         value => userinfo_get($user_name, "locked_pages"));
258         }
259         
260         if ($form->submitted eq 'Logout') {
261                 $session->delete();
262                 print $q->redirect($config{url});
263                 return;
264         }
265         elsif ($form->submitted eq 'Cancel') {
266                 print $q->redirect($config{url});
267                 return;
268         }
269         elsif ($form->submitted eq "Save Preferences" && $form->validate) {
270                 foreach my $field (qw(password email locked_pages)) {
271                         if (length $form->field($field)) {
272                                 userinfo_set($user_name, $field, $form->field($field)) || error("failed to set $field");
273                         }
274                 }
275                 $form->text("Preferences saved.");
276         }
277         
278         print $session->header();
279         print misctemplate($form->title, $form->render(submit => \@buttons));
280 } #}}}
281
282 sub cgi_editpage ($$) { #{{{
283         my $q=shift;
284         my $session=shift;
285
286         eval q{use CGI::FormBuilder};
287         my $form = CGI::FormBuilder->new(
288                 fields => [qw(do rcsinfo subpage from page content comments)],
289                 header => 1,
290                 method => 'POST',
291                 validate => {
292                         content => '/.+/',
293                 },
294                 required => [qw{content}],
295                 javascript => 0,
296                 params => $q,
297                 action => $q->request_uri,
298                 table => 0,
299                 template => "$config{templatedir}/editpage.tmpl"
300         );
301         my @buttons=("Save Page", "Preview", "Cancel");
302         
303         # This untaint is safe because titlepage removes any problimatic
304         # characters.
305         my ($page)=titlepage(possibly_foolish_untaint(lc($form->param('page'))));
306         if (! defined $page || ! length $page ||
307             $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
308                 error("bad page name");
309         }
310         $page=lc($page);
311         
312         my $file=$page.$config{default_pageext};
313         if (exists $pagesources{lc($page)}) {
314                 $file=$pagesources{lc($page)};
315         }
316         my $newfile=0;
317         if (! -e "$config{srcdir}/$file") {
318                 $newfile=1;
319         }
320
321         $form->field(name => "do", type => 'hidden');
322         $form->field(name => "from", type => 'hidden');
323         $form->field(name => "rcsinfo", type => 'hidden');
324         $form->field(name => "subpage", type => 'hidden');
325         $form->field(name => "page", value => "$page", force => 1);
326         $form->field(name => "comments", type => "text", size => 80);
327         $form->field(name => "content", type => "textarea", rows => 20,
328                 cols => 80);
329         $form->tmpl_param("can_commit", $config{rcs});
330         $form->tmpl_param("indexlink", indexlink());
331         $form->tmpl_param("helponformattinglink",
332                 htmllink("", "HelpOnFormatting", 1));
333         $form->tmpl_param("styleurl", styleurl());
334         $form->tmpl_param("baseurl", "$config{url}/");
335         if (! $form->submitted) {
336                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
337                         force => 1);
338         }
339         
340         if ($form->submitted eq "Cancel") {
341                 print $q->redirect("$config{url}/".htmlpage($page));
342                 return;
343         }
344         elsif ($form->submitted eq "Preview") {
345                 require IkiWiki::Render;
346                 $form->tmpl_param("page_preview",
347                         htmlize($config{default_pageext},
348                                 linkify($form->field('content'), $page)));
349         }
350         else {
351                 $form->tmpl_param("page_preview", "");
352         }
353         $form->tmpl_param("page_conflict", "");
354         
355         if (! $form->submitted || $form->submitted eq "Preview" || 
356             ! $form->validate) {
357                 if ($form->field("do") eq "create") {
358                         if (exists $pagesources{lc($page)}) {
359                                 # hmm, someone else made the page in the
360                                 # meantime?
361                                 print $q->redirect("$config{url}/".htmlpage($page));
362                                 return;
363                         }
364                         
365                         my @page_locs;
366                         my $best_loc;
367                         my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
368                         if (! defined $from || ! length $from ||
369                             $from ne $form->param('from') ||
370                             $from=~/$config{wiki_file_prune_regexp}/ ||
371                             $from=~/^\// ||
372                             $form->submitted eq "Preview") {
373                                 @page_locs=$best_loc=$page;
374                         }
375                         else {
376                                 my $dir=$from."/";
377                                 $dir=~s![^/]+/$!!;
378                                 
379                                 if ((defined $form->param('subpage') && length $form->param('subpage')) ||
380                                     $page eq 'discussion') {
381                                         $best_loc="$from/$page";
382                                 }
383                                 else {
384                                         $best_loc=$dir.$page;
385                                 }
386                                 
387                                 push @page_locs, $dir.$page;
388                                 push @page_locs, "$from/$page";
389                                 while (length $dir) {
390                                         $dir=~s![^/]+/$!!;
391                                         push @page_locs, $dir.$page;
392                                 }
393
394                                 @page_locs = grep {
395                                         ! exists $pagesources{lc($_)} &&
396                                         ! page_locked($_, $session, 1)
397                                 } @page_locs;
398                         }
399
400                         $form->tmpl_param("page_select", 1);
401                         $form->field(name => "page", type => 'select',
402                                 options => \@page_locs, value => $best_loc);
403                         $form->title("creating ".pagetitle($page));
404                 }
405                 elsif ($form->field("do") eq "edit") {
406                         page_locked($page, $session);
407                         if (! defined $form->field('content') || 
408                             ! length $form->field('content')) {
409                                 my $content="";
410                                 if (exists $pagesources{lc($page)}) {
411                                         $content=readfile(srcfile($pagesources{lc($page)}));
412                                         $content=~s/\n/\r\n/g;
413                                 }
414                                 $form->field(name => "content", value => $content,
415                                         force => 1);
416                         }
417                         $form->tmpl_param("page_select", 0);
418                         $form->field(name => "page", type => 'hidden');
419                         $form->title("editing ".pagetitle($page));
420                 }
421                 
422                 print $form->render(submit => \@buttons);
423         }
424         else {
425                 # save page
426                 page_locked($page, $session);
427                 
428                 my $content=$form->field('content');
429                 $content=~s/\r\n/\n/g;
430                 $content=~s/\r/\n/g;
431                 writefile($file, $config{srcdir}, $content);
432                 
433                 my $message="web commit ";
434                 if (length $session->param("name")) {
435                         $message.="by ".$session->param("name");
436                 }
437                 else {
438                         $message.="from $ENV{REMOTE_ADDR}";
439                 }
440                 if (defined $form->field('comments') &&
441                     length $form->field('comments')) {
442                         $message.=": ".$form->field('comments');
443                 }
444                 
445                 if ($config{rcs}) {
446                         if ($newfile) {
447                                 rcs_add($file);
448                         }
449                         # prevent deadlock with post-commit hook
450                         unlockwiki();
451                         # presumably the commit will trigger an update
452                         # of the wiki
453                         my $conflict=rcs_commit($file, $message,
454                                 $form->field("rcsinfo"));
455                 
456                         if (defined $conflict) {
457                                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
458                                         force => 1);
459                                 $form->tmpl_param("page_conflict", 1);
460                                 $form->field("content", value => $conflict, force => 1);
461                                 $form->field("do", "edit)");
462                                 $form->tmpl_param("page_select", 0);
463                                 $form->field(name => "page", type => 'hidden');
464                                 $form->title("editing $page");
465                                 print $form->render(submit => \@buttons);
466                                 return;
467                         }
468                 }
469                 else {
470                         require IkiWiki::Render;
471                         refresh();
472                         saveindex();
473                 }
474                 
475                 # The trailing question mark tries to avoid broken
476                 # caches and get the most recent version of the page.
477                 print $q->redirect("$config{url}/".htmlpage($page)."?updated");
478         }
479 } #}}}
480
481 sub cgi_hyperestraier () { #{{{
482         # only works for GET requests
483         chdir("$config{wikistatedir}/hyperestraier") || error("chdir: $!");
484         exec("./".basename($config{cgiurl})) || error("estseek.cgi failed");
485 } #}}}
486
487 sub cgi () { #{{{
488         eval q{use CGI};
489         eval q{use CGI::Session};
490         
491         my $q=CGI->new;
492         
493         my $do=$q->param('do');
494         if (! defined $do || ! length $do) {
495                 if (defined $q->param('phrase')) {
496                         cgi_hyperestraier();
497                 }
498                 else {
499                         error("\"do\" parameter missing");
500                 }
501         }
502         
503         # Things that do not need a session.
504         if ($do eq 'recentchanges') {
505                 cgi_recentchanges($q);
506                 return;
507         }
508         elsif ($do eq 'hyperestraier') {
509                 cgi_hyperestraier();
510         }
511         
512         CGI::Session->name("ikiwiki_session_$config{wikiname}");
513         
514         my $oldmask=umask(077);
515         my $session = CGI::Session->new("driver:DB_File", $q,
516                 { FileName => "$config{wikistatedir}/sessions.db" });
517         umask($oldmask);
518         
519         # Everything below this point needs the user to be signed in.
520         if ((! $config{anonok} && ! defined $session->param("name") ||
521              ! defined $session->param("name") ||
522              ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
523                 cgi_signin($q, $session);
524         
525                 # Force session flush with safe umask.
526                 my $oldmask=umask(077);
527                 $session->flush;
528                 umask($oldmask);
529                 
530                 return;
531         }
532         
533         if ($do eq 'create' || $do eq 'edit') {
534                 cgi_editpage($q, $session);
535         }
536         elsif ($do eq 'prefs') {
537                 cgi_prefs($q, $session);
538         }
539         elsif ($do eq 'blog') {
540                 my $page=titlepage(lc($q->param('title')));
541                 # if the page already exists, munge it to be unique
542                 my $from=$q->param('from');
543                 my $add="";
544                 while (exists $oldpagemtime{"$from/$page$add"}) {
545                         $add=1 unless length $add;
546                         $add++;
547                 }
548                 $q->param('page', $page.$add);
549                 # now run same as create
550                 $q->param('do', 'create');
551                 cgi_editpage($q, $session);
552         }
553         else {
554                 error("unknown do parameter");
555         }
556 } #}}}
557
558 1