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