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