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