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