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