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