admin prefs move to setup file, stage 1
[ikiwiki.git] / IkiWiki / Plugin / attachment.pm
1 #!/usr/bin/perl
2 package IkiWiki::Plugin::attachment;
3
4 use warnings;
5 use strict;
6 use IkiWiki 2.00;
7
8 sub import { #{{{
9         hook(type => "getsetup", id => "attachment", call => \&getsetup);
10         hook(type => "checkconfig", id => "attachment", call => \&checkconfig);
11         hook(type => "formbuilder_setup", id => "attachment", call => \&formbuilder_setup);
12         hook(type => "formbuilder", id => "attachment", call => \&formbuilder);
13 } # }}}
14
15 sub getsetup () { #{{{
16         return
17                 virus_checker => {
18                         type => "string",
19                         example => "clamdscan -",
20                         description => "virus checker program (reads STDIN, returns nonzero if virus found)",
21                         safe => 0, # executed
22                         rebuild => 0,
23                 },
24                 allowed_attachments => {
25                         type => "string",
26                         example => "mimetype(image/*) and maxsize(50kb)",
27                         description => "enhanced PageSpec specifying what attachments are allowed",
28                         description_html => htmllink("", "", 
29                                 "ikiwiki/PageSpec/attachment", 
30                                 noimageinline => 1,
31                                 linktext => "enhanced PageSpec",
32                                 )." specifying what attachments are allowed",
33                         safe => 1,
34                         rebuild => 0,
35                 },
36 } #}}}
37
38 sub check_canattach ($$;$) { #{{{
39         my $session=shift;
40         my $dest=shift; # where it's going to be put, under the srcdir
41         my $file=shift; # the path to the attachment currently
42
43         # Don't allow an attachment to be uploaded with the same name as an
44         # existing page.
45         if (exists $pagesources{$dest} && $pagesources{$dest} ne $dest) {
46                 error(sprintf(gettext("there is already a page named %s"), $dest));
47         }
48
49         # Use a special pagespec to test that the attachment is valid.
50         my $allowed=1;
51         if (defined $config{allowed_attachments} &&
52             length $config{allowed_attachments}) {
53                 $allowed=pagespec_match($dest,
54                         $config{allowed_attachments},
55                         file => $file,
56                         user => $session->param("name"),
57                         ip => $ENV{REMOTE_ADDR},
58                 );
59         }
60
61         # XXX deprecated, should be removed eventually
62         if ($allowed) {
63                 foreach my $admin (@{$config{adminuser}}) {
64                         my $allowed_attachments=IkiWiki::userinfo_get($admin, "allowed_attachments");
65                         if (defined $allowed_attachments &&
66                             length $allowed_attachments) {
67                                 $allowed=pagespec_match($dest,
68                                         $allowed_attachments,
69                                         file => $file,
70                                         user => $session->param("name"),
71                                         ip => $ENV{REMOTE_ADDR},
72                                 );
73                                 last if $allowed;
74                         }
75                 }
76         }
77
78         if (! $allowed) {
79                 error(gettext("prohibited by allowed_attachments")." ($allowed)");
80         }
81         else {
82                 return 1;
83         }
84 } #}}}
85
86 sub checkconfig () { #{{{
87         $config{cgi_disable_uploads}=0;
88 } #}}}
89
90 sub formbuilder_setup (@) { #{{{
91         my %params=@_;
92         my $form=$params{form};
93         my $q=$params{cgi};
94
95         if (defined $form->field("do") && $form->field("do") eq "edit") {
96                 # Add attachment field, set type to multipart.
97                 $form->enctype(&CGI::MULTIPART);
98                 $form->field(name => 'attachment', type => 'file');
99                 # These buttons are not put in the usual place, so
100                 # are not added to the normal formbuilder button list.
101                 $form->tmpl_param("field-upload" => '<input name="_submit" type="submit" value="Upload Attachment" />');
102                 $form->tmpl_param("field-link" => '<input name="_submit" type="submit" value="Insert Links" />');
103
104                 # Add the javascript from the toggle plugin;
105                 # the attachments interface uses it to toggle visibility.
106                 require IkiWiki::Plugin::toggle;
107                 $form->tmpl_param("javascript" => $IkiWiki::Plugin::toggle::javascript);
108                 # Start with the attachments interface toggled invisible,
109                 # but if it was used, keep it open.
110                 if ($form->submitted ne "Upload Attachment" &&
111                     (! defined $q->param("attachment_select") ||
112                     ! length $q->param("attachment_select"))) {
113                         $form->tmpl_param("attachments-class" => "toggleable");
114                 }
115                 else {
116                         $form->tmpl_param("attachments-class" => "toggleable-open");
117                 }
118         }
119         elsif ($form->title eq "preferences") {
120                 # XXX deprecated, should remove eventually
121                 my $session=$params{session};
122                 my $user_name=$session->param("name");
123
124                 $form->field(name => "allowed_attachments", size => 50,
125                         fieldset => "admin",
126                         comment => "deprecated; please move to allowed_attachments in setup file",
127                 );
128                 if (! IkiWiki::is_admin($user_name)) {
129                         $form->field(name => "allowed_attachments", type => "hidden");
130                 }
131                 if (! $form->submitted) {
132                         my $value=IkiWiki::userinfo_get($user_name, "allowed_attachments");
133                         if (length $value) {
134                                 $form->field(name => "allowed_attachments", force => 1,
135                                         value => IkiWiki::userinfo_get($user_name, "allowed_attachments"));
136                         }
137                         else {
138                                 $form->field(name => "allowed_attachments", type => "hidden");
139                         }
140                 }
141                 if ($form->submitted && $form->submitted eq 'Save Preferences') {
142                         if (defined $form->field("allowed_attachments")) {
143                                 IkiWiki::userinfo_set($user_name, "allowed_attachments",
144                                 $form->field("allowed_attachments")) ||
145                                         error("failed to set allowed_attachments");
146                         }
147                 }
148         }
149 } #}}}
150
151 sub formbuilder (@) { #{{{
152         my %params=@_;
153         my $form=$params{form};
154         my $q=$params{cgi};
155
156         return if ! defined $form->field("do") || $form->field("do") ne "edit";
157
158         my $filename=$q->param('attachment');
159         if (defined $filename && length $filename &&
160             ($form->submitted eq "Upload Attachment" || $form->submitted eq "Save Page")) {
161                 my $session=$params{session};
162                 
163                 # This is an (apparently undocumented) way to get the name
164                 # of the temp file that CGI writes the upload to.
165                 my $tempfile=$q->tmpFileName($filename);
166                 if (! defined $tempfile || ! length $tempfile) {
167                         # perl 5.8 needs an alternative, awful method
168                         if ($q =~ /HASH/ && exists $q->{'.tmpfiles'}) {
169                                 foreach my $key (keys(%{$q->{'.tmpfiles'}})) {
170                                         $tempfile=$q->tmpFileName(\$key);
171                                         last if defined $tempfile && length $tempfile;
172                                 }
173                         }
174                         if (! defined $tempfile || ! length $tempfile) {
175                                 error("CGI::tmpFileName failed to return the uploaded file name");
176                         }
177                 }
178
179                 $filename=IkiWiki::linkpage(
180                         IkiWiki::possibly_foolish_untaint(
181                                 attachment_location($form->field('page')).
182                                 IkiWiki::basename($filename)));
183                 if (IkiWiki::file_pruned($filename, $config{srcdir})) {
184                         error(gettext("bad attachment filename"));
185                 }
186                 
187                 # Check that the user is allowed to edit a page with the
188                 # name of the attachment.
189                 IkiWiki::check_canedit($filename, $q, $session, 1);
190                 # And that the attachment itself is acceptable.
191                 check_canattach($session, $filename, $tempfile);
192
193                 # Needed for fast_file_copy and for rendering below.
194                 require IkiWiki::Render;
195
196                 # Move the attachment into place.
197                 # Try to use a fast rename; fall back to copying.
198                 IkiWiki::prep_writefile($filename, $config{srcdir});
199                 unlink($config{srcdir}."/".$filename);
200                 if (rename($tempfile, $config{srcdir}."/".$filename)) {
201                         # The temp file has tight permissions; loosen up.
202                         chmod(0666 & ~umask, $config{srcdir}."/".$filename);
203                 }
204                 else {
205                         my $fh=$q->upload('attachment');
206                         if (! defined $fh || ! ref $fh) {
207                                 # needed by old CGI versions
208                                 $fh=$q->param('attachment');
209                                 if (! defined $fh || ! ref $fh) {
210                                         # even that doesn't always work,
211                                         # fall back to opening the tempfile
212                                         $fh=undef;
213                                         open($fh, "<", $tempfile) || error("failed to open \"$tempfile\": $!");
214                                 }
215                         }
216                         binmode($fh);
217                         writefile($filename, $config{srcdir}, undef, 1, sub {
218                                 IkiWiki::fast_file_copy($tempfile, $filename, $fh, @_);
219                         });
220                 }
221
222                 # Check the attachment in and trigger a wiki refresh.
223                 if ($config{rcs}) {
224                         IkiWiki::rcs_add($filename);
225                         IkiWiki::disable_commit_hook();
226                         IkiWiki::rcs_commit($filename, gettext("attachment upload"),
227                                 IkiWiki::rcs_prepedit($filename),
228                                 $session->param("name"), $ENV{REMOTE_ADDR});
229                         IkiWiki::enable_commit_hook();
230                         IkiWiki::rcs_update();
231                 }
232                 IkiWiki::refresh();
233                 IkiWiki::saveindex();
234         }
235         elsif ($form->submitted eq "Insert Links") {
236                 my $page=quotemeta($q->param("page"));
237                 my $add="";
238                 foreach my $f ($q->param("attachment_select")) {
239                         $f=~s/^$page\///;
240                         $add.="[[$f]]\n";
241                 }
242                 $form->field(name => 'editcontent',
243                         value => $form->field('editcontent')."\n\n".$add,
244                         force => 1) if length $add;
245         }
246         
247         # Generate the attachment list only after having added any new
248         # attachments.
249         $form->tmpl_param("attachment_list" => [attachment_list($form->field('page'))]);
250 } # }}}
251
252 sub attachment_location ($) { #{{{
253         my $page=shift;
254         
255         # Put the attachment in a subdir of the page it's attached
256         # to, unless that page is an "index" page.
257         $page=~s/(^|\/)index//;
258         $page.="/" if length $page;
259         
260         return $page;
261 } #}}}
262
263 sub attachment_list ($) { #{{{
264         my $page=shift;
265         my $loc=attachment_location($page);
266
267         my @ret;
268         foreach my $f (values %pagesources) {
269                 if (! defined IkiWiki::pagetype($f) &&
270                     $f=~m/^\Q$loc\E[^\/]+$/ &&
271                     -e "$config{srcdir}/$f") {
272                         push @ret, {
273                                 "field-select" => '<input type="checkbox" name="attachment_select" value="'.$f.'" />',
274                                 link => htmllink($page, $page, $f, noimageinline => 1),
275                                 size => humansize((stat(_))[7]),
276                                 mtime => displaytime($IkiWiki::pagemtime{$f}),
277                                 mtime_raw => $IkiWiki::pagemtime{$f},
278                         };
279                 }
280         }
281
282         # Sort newer attachments to the top of the list, so a newly-added
283         # attachment appears just before the form used to add it.
284         return sort { $b->{mtime_raw} <=> $a->{mtime_raw} || $a->{link} cmp $b->{link} } @ret;
285 } #}}}
286
287 my %units=( #{{{        # size in bytes
288         B               => 1,
289         byte            => 1,
290         KB              => 2 ** 10,
291         kilobyte        => 2 ** 10,
292         K               => 2 ** 10,
293         KB              => 2 ** 10,
294         kilobyte        => 2 ** 10,
295         M               => 2 ** 20,
296         MB              => 2 ** 20,
297         megabyte        => 2 ** 20,
298         G               => 2 ** 30,
299         GB              => 2 ** 30,
300         gigabyte        => 2 ** 30,
301         T               => 2 ** 40,
302         TB              => 2 ** 40,
303         terabyte        => 2 ** 40,
304         P               => 2 ** 50,
305         PB              => 2 ** 50,
306         petabyte        => 2 ** 50,
307         E               => 2 ** 60,
308         EB              => 2 ** 60,
309         exabyte         => 2 ** 60,
310         Z               => 2 ** 70,
311         ZB              => 2 ** 70,
312         zettabyte       => 2 ** 70,
313         Y               => 2 ** 80,
314         YB              => 2 ** 80,
315         yottabyte       => 2 ** 80,
316         # ikiwiki, if you find you need larger data quantities, either modify
317         # yourself to add them, or travel back in time to 2008 and kill me.
318         #   -- Joey
319 ); #}}}
320
321 sub parsesize ($) { #{{{
322         my $size=shift;
323
324         no warnings;
325         my $base=$size+0; # force to number
326         use warnings;
327         foreach my $unit (sort keys %units) {
328                 if ($size=~/[0-9\s]\Q$unit\E$/i) {
329                         return $base * $units{$unit};
330                 }
331         }
332         return $base;
333 } #}}}
334
335 sub humansize ($) { #{{{
336         my $size=shift;
337
338         foreach my $unit (reverse sort { $units{$a} <=> $units{$b} || $b cmp $a } keys %units) {
339                 if ($size / $units{$unit} > 0.25) {
340                         return (int($size / $units{$unit} * 10)/10).$unit;
341                 }
342         }
343         return $size; # near zero, or negative
344 } #}}}
345
346 package IkiWiki::PageSpec;
347
348 sub match_maxsize ($$;@) { #{{{
349         shift;
350         my $maxsize=eval{IkiWiki::Plugin::attachment::parsesize(shift)};
351         if ($@) {
352                 return IkiWiki::FailReason->new("unable to parse maxsize (or number too large)");
353         }
354
355         my %params=@_;
356         if (! exists $params{file}) {
357                 return IkiWiki::FailReason->new("no file specified");
358         }
359
360         if (-s $params{file} > $maxsize) {
361                 return IkiWiki::FailReason->new("file too large (".(-s $params{file})." >  $maxsize)");
362         }
363         else {
364                 return IkiWiki::SuccessReason->new("file not too large");
365         }
366 } #}}}
367
368 sub match_minsize ($$;@) { #{{{
369         shift;
370         my $minsize=eval{IkiWiki::Plugin::attachment::parsesize(shift)};
371         if ($@) {
372                 return IkiWiki::FailReason->new("unable to parse minsize (or number too large)");
373         }
374
375         my %params=@_;
376         if (! exists $params{file}) {
377                 return IkiWiki::FailReason->new("no file specified");
378         }
379
380         if (-s $params{file} < $minsize) {
381                 return IkiWiki::FailReason->new("file too small");
382         }
383         else {
384                 return IkiWiki::SuccessReason->new("file not too small");
385         }
386 } #}}}
387
388 sub match_mimetype ($$;@) { #{{{
389         shift;
390         my $wanted=shift;
391
392         my %params=@_;
393         if (! exists $params{file}) {
394                 return IkiWiki::FailReason->new("no file specified");
395         }
396
397         # Use ::magic to get the mime type, the idea is to only trust
398         # data obtained by examining the actual file contents.
399         eval q{use File::MimeInfo::Magic};
400         if ($@) {
401                 return IkiWiki::FailReason->new("failed to load File::MimeInfo::Magic ($@); cannot check MIME type");
402         }
403         my $mimetype=File::MimeInfo::Magic::magic($params{file});
404         if (! defined $mimetype) {
405                 $mimetype="unknown";
406         }
407
408         my $regexp=IkiWiki::glob2re($wanted);
409         if ($mimetype!~/^$regexp$/i) {
410                 return IkiWiki::FailReason->new("file MIME type is $mimetype, not $wanted");
411         }
412         else {
413                 return IkiWiki::SuccessReason->new("file MIME type is $mimetype");
414         }
415 } #}}}
416
417 sub match_virusfree ($$;@) { #{{{
418         shift;
419         my $wanted=shift;
420
421         my %params=@_;
422         if (! exists $params{file}) {
423                 return IkiWiki::FailReason->new("no file specified");
424         }
425
426         if (! exists $IkiWiki::config{virus_checker} ||
427             ! length $IkiWiki::config{virus_checker}) {
428                 return IkiWiki::FailReason->new("no virus_checker configured");
429         }
430
431         # The file needs to be fed into the virus checker on stdin,
432         # because the file is not world-readable, and if clamdscan is
433         # used, clamd would fail to read it.
434         eval q{use IPC::Open2};
435         error($@) if $@;
436         open (IN, "<", $params{file}) || return IkiWiki::FailReason->new("failed to read file");
437         binmode(IN);
438         my $sigpipe=0;
439         $SIG{PIPE} = sub { $sigpipe=1 };
440         my $pid=open2(\*CHECKER_OUT, "<&IN", $IkiWiki::config{virus_checker}); 
441         my $reason=<CHECKER_OUT>;
442         chomp $reason;
443         1 while (<CHECKER_OUT>);
444         close(CHECKER_OUT);
445         waitpid $pid, 0;
446         $SIG{PIPE}="DEFAULT";
447         if ($sigpipe || $?) {
448                 if (! length $reason) {
449                         $reason="virus checker $IkiWiki::config{virus_checker}; failed with no output";
450                 }
451                 return IkiWiki::FailReason->new("file seems to contain a virus ($reason)");
452         }
453         else {
454                 return IkiWiki::SuccessReason->new("file seems virusfree ($reason)");
455         }
456 } #}}}
457
458 sub match_ispage ($$;@) { #{{{
459         my $filename=shift;
460
461         if (defined IkiWiki::pagetype($filename)) {
462                 return IkiWiki::SuccessReason->new("file is a wiki page");
463         }
464         else {
465                 return IkiWiki::FailReason->new("file is not a wiki page");
466         }
467 } #}}}
468
469 sub match_user ($$;@) { #{{{
470         shift;
471         my $user=shift;
472         my %params=@_;
473         
474         if (! exists $params{user}) {
475                 return IkiWiki::FailReason->new("no user specified");
476         }
477
478         if (defined $params{user} && lc $params{user} eq lc $user) {
479                 return IkiWiki::SuccessReason->new("user is $user");
480         }
481         elsif (! defined $params{user}) {
482                 return IkiWiki::FailReason->new("not logged in");
483         }
484         else {
485                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
486         }
487 } #}}}
488
489 sub match_ip ($$;@) { #{{{
490         shift;
491         my $ip=shift;
492         my %params=@_;
493         
494         if (! exists $params{ip}) {
495                 return IkiWiki::FailReason->new("no IP specified");
496         }
497
498         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
499                 return IkiWiki::SuccessReason->new("IP is $ip");
500         }
501         else {
502                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
503         }
504 } #}}}
505
506 1