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