4f4c488762ee477245cb3ad79dc39ae449fdac59
[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                 require Encode;
357                 my $content = Encode::decode_utf8($form->field('editcontent'));
358                 $form->field(name => "editcontent", value => $content, force => 1);
359                 $form->tmpl_param("page_preview",
360                         Encode::decode_utf8(htmlize($config{default_pageext},
361                                 linkify($page, $page, $content))));
362         }
363         else {
364                 $form->tmpl_param("page_preview", "");
365         }
366         $form->tmpl_param("page_conflict", "");
367         
368         if (! $form->submitted || $form->submitted eq "Preview" || 
369             ! $form->validate) {
370                 if ($form->field("do") eq "create") {
371                         my @page_locs;
372                         my $best_loc;
373                         my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
374                         if (! defined $from || ! length $from ||
375                             $from ne $form->param('from') ||
376                             $from=~/$config{wiki_file_prune_regexp}/ ||
377                             $from=~/^\// ||
378                             $form->submitted eq "Preview") {
379                                 @page_locs=$best_loc=$page;
380                         }
381                         else {
382                                 my $dir=$from."/";
383                                 $dir=~s![^/]+/+$!!;
384                                 
385                                 if ((defined $form->param('subpage') && length $form->param('subpage')) ||
386                                     $page eq 'discussion') {
387                                         $best_loc="$from/$page";
388                                 }
389                                 else {
390                                         $best_loc=$dir.$page;
391                                 }
392                                 
393                                 push @page_locs, $dir.$page;
394                                 push @page_locs, "$from/$page";
395                                 while (length $dir) {
396                                         $dir=~s![^/]+/+$!!;
397                                         push @page_locs, $dir.$page;
398                                 }
399                         }
400
401                         @page_locs = grep {
402                                 ! exists $pagesources{lc($_)} &&
403                                 ! page_locked($_, $session, 1)
404                         } @page_locs;
405                         
406                         if (! @page_locs) {
407                                 # hmm, someone else made the page in the
408                                 # meantime?
409                                 print $q->redirect("$config{url}/".htmlpage($page));
410                                 return;
411                         }
412                                 
413                         $form->tmpl_param("page_select", 1);
414                         $form->field(name => "page", type => 'select',
415                                 options => \@page_locs, value => $best_loc);
416                         $form->title("creating ".pagetitle($page));
417                 }
418                 elsif ($form->field("do") eq "edit") {
419                         page_locked($page, $session);
420                         if (! defined $form->field('editcontent') || 
421                             ! length $form->field('editcontent')) {
422                                 my $content="";
423                                 if (exists $pagesources{lc($page)}) {
424                                         require Encode;
425                                         $content=Encode::decode_utf8(readfile(srcfile($pagesources{lc($page)})));
426                                         $content=~s/\n/\r\n/g;
427                                 }
428                                 $form->field(name => "editcontent", value => $content,
429                                         force => 1);
430                         }
431                         $form->tmpl_param("page_select", 0);
432                         $form->field(name => "page", type => 'hidden');
433                         $form->title("editing ".pagetitle($page));
434                 }
435                 
436                 print $form->render(submit => \@buttons);
437         }
438         else {
439                 # save page
440                 page_locked($page, $session);
441                 
442                 my $content=$form->field('editcontent');
443                 $content=~s/\r\n/\n/g;
444                 $content=~s/\r/\n/g;
445                 writefile($file, $config{srcdir}, $content);
446                 
447                 my $message="web commit ";
448                 if (length $session->param("name")) {
449                         $message.="by ".$session->param("name");
450                 }
451                 else {
452                         $message.="from $ENV{REMOTE_ADDR}";
453                 }
454                 if (defined $form->field('comments') &&
455                     length $form->field('comments')) {
456                         require Encode;
457                         $message.=Encode::decode_utf8(": ".$form->field('comments'));
458                 }
459                 
460                 if ($config{rcs}) {
461                         if ($newfile) {
462                                 rcs_add($file);
463                         }
464                         # prevent deadlock with post-commit hook
465                         unlockwiki();
466                         # presumably the commit will trigger an update
467                         # of the wiki
468                         my $conflict=rcs_commit($file, $message,
469                                 $form->field("rcsinfo"));
470                 
471                         if (defined $conflict) {
472                                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
473                                         force => 1);
474                                 $form->tmpl_param("page_conflict", 1);
475                                 $form->field("editcontent", value => $conflict, force => 1);
476                                 $form->field("do", "edit)");
477                                 $form->tmpl_param("page_select", 0);
478                                 $form->field(name => "page", type => 'hidden');
479                                 $form->title("editing $page");
480                                 print $form->render(submit => \@buttons);
481                                 return;
482                         }
483                 }
484                 else {
485                         require IkiWiki::Render;
486                         refresh();
487                         saveindex();
488                 }
489                 
490                 # The trailing question mark tries to avoid broken
491                 # caches and get the most recent version of the page.
492                 print $q->redirect("$config{url}/".htmlpage($page)."?updated");
493         }
494 } #}}}
495
496 sub cgi () { #{{{
497         eval q{use CGI};
498         eval q{use CGI::Session};
499         
500         my $q=CGI->new;
501         
502         if (exists $hooks{cgi}) {
503                 foreach my $id (keys %{$hooks{cgi}}) {
504                         $hooks{cgi}{$id}{call}->($q);
505                 }
506         }
507         
508         my $do=$q->param('do');
509         if (! defined $do || ! length $do) {
510                 error("\"do\" parameter missing");
511         }
512         
513         # Things that do not need a session.
514         if ($do eq 'recentchanges') {
515                 cgi_recentchanges($q);
516                 return;
517         }
518         elsif ($do eq 'hyperestraier') {
519                 cgi_hyperestraier();
520         }
521         
522         CGI::Session->name("ikiwiki_session_$config{wikiname}");
523         
524         my $oldmask=umask(077);
525         my $session = CGI::Session->new("driver:DB_File", $q,
526                 { FileName => "$config{wikistatedir}/sessions.db" });
527         umask($oldmask);
528         
529         # Everything below this point needs the user to be signed in.
530         if ((! $config{anonok} &&
531              (! defined $session->param("name") ||
532              ! userinfo_get($session->param("name"), "regdate"))) || $do eq 'signin') {
533                 cgi_signin($q, $session);
534         
535                 # Force session flush with safe umask.
536                 my $oldmask=umask(077);
537                 $session->flush;
538                 umask($oldmask);
539                 
540                 return;
541         }
542         
543         if ($do eq 'create' || $do eq 'edit') {
544                 cgi_editpage($q, $session);
545         }
546         elsif ($do eq 'prefs') {
547                 cgi_prefs($q, $session);
548         }
549         elsif ($do eq 'blog') {
550                 my $page=titlepage(lc($q->param('title')));
551                 # if the page already exists, munge it to be unique
552                 my $from=$q->param('from');
553                 my $add="";
554                 while (exists $oldpagemtime{"$from/$page$add"}) {
555                         $add=1 unless length $add;
556                         $add++;
557                 }
558                 $q->param('page', $page.$add);
559                 # now run same as create
560                 $q->param('do', 'create');
561                 cgi_editpage($q, $session);
562         }
563         else {
564                 error("unknown do parameter");
565         }
566 } #}}}
567
568 1