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