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