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