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