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