another sub, wow
[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         loadindex();
275         
276         eval q{use CGI::FormBuilder};
277         my $form = CGI::FormBuilder->new(
278                 fields => [qw(do rcsinfo from page content comments)],
279                 header => 1,
280                 method => 'POST',
281                 validate => {
282                         content => '/.+/',
283                 },
284                 required => [qw{content}],
285                 javascript => 0,
286                 params => $q,
287                 action => $q->request_uri,
288                 table => 0,
289                 template => "$config{templatedir}/editpage.tmpl"
290         );
291         my @buttons=("Save Page", "Preview", "Cancel");
292         
293         my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
294         if (! defined $page || ! length $page || $page ne $q->param('page') ||
295             $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
296                 error("bad page name");
297         }
298         $page=lc($page);
299         
300         my $file=$page.$config{default_pageext};
301         my $newfile=1;
302         if (exists $pagesources{lc($page)}) {
303                 $file=$pagesources{lc($page)};
304                 $newfile=0;
305         }
306
307         $form->field(name => "do", type => 'hidden');
308         $form->field(name => "from", type => 'hidden');
309         $form->field(name => "rcsinfo", type => 'hidden');
310         $form->field(name => "page", value => "$page", force => 1);
311         $form->field(name => "comments", type => "text", size => 80);
312         $form->field(name => "content", type => "textarea", rows => 20,
313                 cols => 80);
314         $form->tmpl_param("can_commit", $config{rcs});
315         $form->tmpl_param("indexlink", indexlink());
316         $form->tmpl_param("helponformattinglink",
317                 htmllink("", "HelpOnFormatting", 1));
318         if (! $form->submitted) {
319                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
320                         force => 1);
321         }
322         
323         if ($form->submitted eq "Cancel") {
324                 print $q->redirect("$config{url}/".htmlpage($page));
325                 return;
326         }
327         elsif ($form->submitted eq "Preview") {
328                 require IkiWiki::Render;
329                 $form->tmpl_param("page_preview",
330                         htmlize($config{default_pageext},
331                                 linkify($form->field('content'), $page)));
332         }
333         else {
334                 $form->tmpl_param("page_preview", "");
335         }
336         $form->tmpl_param("page_conflict", "");
337         
338         if (! $form->submitted || $form->submitted eq "Preview" || 
339             ! $form->validate) {
340                 if ($form->field("do") eq "create") {
341                         if (exists $pagesources{lc($page)}) {
342                                 # hmm, someone else made the page in the
343                                 # meantime?
344                                 print $q->redirect("$config{url}/".htmlpage($page));
345                                 return;
346                         }
347                         
348                         my @page_locs;
349                         my $best_loc;
350                         my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
351                         if (! defined $from || ! length $from ||
352                             $from ne $form->param('from') ||
353                             $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
354                                 @page_locs=$best_loc=$page;
355                         }
356                         else {
357                                 my $dir=$from."/";
358                                 $dir=~s![^/]+/$!!;
359                                 
360                                 if ($page eq 'discussion') {
361                                         $best_loc="$from/$page";
362                                 }
363                                 else {
364                                         $best_loc=$dir.$page;
365                                 }
366                                 
367                                 push @page_locs, $dir.$page;
368                                 push @page_locs, "$from/$page";
369                                 while (length $dir) {
370                                         $dir=~s![^/]+/$!!;
371                                         push @page_locs, $dir.$page;
372                                 }
373
374                                 @page_locs = grep {
375                                         ! exists $pagesources{lc($_)} &&
376                                         ! page_locked($_, $session, 1)
377                                 } @page_locs;
378                         }
379
380                         $form->tmpl_param("page_select", 1);
381                         $form->field(name => "page", type => 'select',
382                                 options => \@page_locs, value => $best_loc);
383                         $form->title("creating $page");
384                 }
385                 elsif ($form->field("do") eq "edit") {
386                         page_locked($page, $session);
387                         if (! defined $form->field('content') || 
388                             ! length $form->field('content')) {
389                                 my $content="";
390                                 if (exists $pagesources{lc($page)}) {
391                                         $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
392                                         $content=~s/\n/\r\n/g;
393                                 }
394                                 $form->field(name => "content", value => $content,
395                                         force => 1);
396                         }
397                         $form->tmpl_param("page_select", 0);
398                         $form->field(name => "page", type => 'hidden');
399                         $form->title("editing $page");
400                 }
401                 
402                 print $form->render(submit => \@buttons);
403         }
404         else {
405                 # save page
406                 page_locked($page, $session);
407                 
408                 my $content=$form->field('content');
409                 $content=~s/\r\n/\n/g;
410                 $content=~s/\r/\n/g;
411                 writefile("$config{srcdir}/$file", $content);
412                 
413                 my $message="web commit ";
414                 if (length $session->param("name")) {
415                         $message.="by ".$session->param("name");
416                 }
417                 else {
418                         $message.="from $ENV{REMOTE_ADDR}";
419                 }
420                 if (defined $form->field('comments') &&
421                     length $form->field('comments')) {
422                         $message.=": ".$form->field('comments');
423                 }
424                 
425                 if ($config{rcs}) {
426                         if ($newfile) {
427                                 rcs_add($file);
428                         }
429                         # prevent deadlock with post-commit hook
430                         unlockwiki();
431                         # presumably the commit will trigger an update
432                         # of the wiki
433                         my $conflict=rcs_commit($file, $message,
434                                 $form->field("rcsinfo"));
435                 
436                         if (defined $conflict) {
437                                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
438                                         force => 1);
439                                 $form->tmpl_param("page_conflict", 1);
440                                 $form->field("content", value => $conflict, force => 1);
441                                 $form->field("do", "edit)");
442                                 $form->tmpl_param("page_select", 0);
443                                 $form->field(name => "page", type => 'hidden');
444                                 $form->title("editing $page");
445                                 print $form->render(submit => \@buttons);
446                                 return;
447                         }
448                 }
449                 else {
450                         require IkiWiki::Render;
451                         refresh();
452                         saveindex();
453                 }
454                 
455                 # The trailing question mark tries to avoid broken
456                 # caches and get the most recent version of the page.
457                 print $q->redirect("$config{url}/".htmlpage($page)."?updated");
458         }
459 } #}}}
460
461 sub cgi () { #{{{
462         eval q{use CGI};
463         eval q{use CGI::Session};
464         
465         my $q=CGI->new;
466         
467         my $do=$q->param('do');
468         if (! defined $do || ! length $do) {
469                 error("\"do\" parameter missing");
470         }
471         
472         # This does not need a session.
473         if ($do eq 'recentchanges') {
474                 cgi_recentchanges($q);
475                 return;
476         }
477         
478         CGI::Session->name("ikiwiki_session");
479
480         my $oldmask=umask(077);
481         my $session = CGI::Session->new("driver:db_file", $q,
482                 { FileName => "$config{wikistatedir}/sessions.db" });
483         umask($oldmask);
484         
485         # Everything below this point needs the user to be signed in.
486         if ((! $config{anonok} && ! defined $session->param("name") ||
487              ! defined $session->param("name") ||
488              ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
489                 cgi_signin($q, $session);
490         
491                 # Force session flush with safe umask.
492                 my $oldmask=umask(077);
493                 $session->flush;
494                 umask($oldmask);
495                 
496                 return;
497         }
498         
499         if ($do eq 'create' || $do eq 'edit') {
500                 cgi_editpage($q, $session);
501         }
502         elsif ($do eq 'prefs') {
503                 cgi_prefs($q, $session);
504         }
505         else {
506                 error("unknown do parameter");
507         }
508 } #}}}
509
510 1