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