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