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