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