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