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