]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/attachment.pm
added getsetup hooks for all plugins up to recentchanges
[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                  => {
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 } #}}}
26
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
31
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         }
37
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 } #}}}
60
61 sub checkconfig () { #{{{
62         $config{cgi_disable_uploads}=0;
63 } #}}}
64
65 sub formbuilder_setup (@) { #{{{
66         my %params=@_;
67         my $form=$params{form};
68         my $q=$params{cgi};
69
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" />');
78
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");
97
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 } #}}}
123
124 sub formbuilder (@) { #{{{
125         my %params=@_;
126         my $form=$params{form};
127         my $q=$params{cgi};
128
129         return if ! defined $form->field("do") || $form->field("do") ne "edit";
130
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                 }
151
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);
165
166                 # Needed for fast_file_copy and for rendering below.
167                 require IkiWiki::Render;
168
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                 }
194
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 $add="";
210                 foreach my $f ($q->param("attachment_select")) {
211                         $add.="[[$f]]\n";
212                 }
213                 $form->field(name => 'editcontent',
214                         value => $form->field('editcontent')."\n\n".$add,
215                         force => 1) if length $add;
216         }
217         
218         # Generate the attachment list only after having added any new
219         # attachments.
220         $form->tmpl_param("attachment_list" => [attachment_list($form->field('page'))]);
221 } # }}}
222
223 sub attachment_location ($) { #{{{
224         my $page=shift;
225         
226         # Put the attachment in a subdir of the page it's attached
227         # to, unless that page is an "index" page.
228         $page=~s/(^|\/)index//;
229         $page.="/" if length $page;
230         
231         return $page;
232 } #}}}
233
234 sub attachment_list ($) { #{{{
235         my $page=shift;
236         my $loc=attachment_location($page);
237
238         my @ret;
239         foreach my $f (values %pagesources) {
240                 if (! defined IkiWiki::pagetype($f) &&
241                     $f=~m/^\Q$loc\E[^\/]+$/ &&
242                     -e "$config{srcdir}/$f") {
243                         push @ret, {
244                                 "field-select" => '<input type="checkbox" name="attachment_select" value="'.$f.'" />',
245                                 link => htmllink($page, $page, $f, noimageinline => 1),
246                                 size => humansize((stat(_))[7]),
247                                 mtime => displaytime($IkiWiki::pagemtime{$f}),
248                                 mtime_raw => $IkiWiki::pagemtime{$f},
249                         };
250                 }
251         }
252
253         # Sort newer attachments to the top of the list, so a newly-added
254         # attachment appears just before the form used to add it.
255         return sort { $b->{mtime_raw} <=> $a->{mtime_raw} || $a->{link} cmp $b->{link} } @ret;
256 } #}}}
257
258 my %units=( #{{{        # size in bytes
259         B               => 1,
260         byte            => 1,
261         KB              => 2 ** 10,
262         kilobyte        => 2 ** 10,
263         K               => 2 ** 10,
264         KB              => 2 ** 10,
265         kilobyte        => 2 ** 10,
266         M               => 2 ** 20,
267         MB              => 2 ** 20,
268         megabyte        => 2 ** 20,
269         G               => 2 ** 30,
270         GB              => 2 ** 30,
271         gigabyte        => 2 ** 30,
272         T               => 2 ** 40,
273         TB              => 2 ** 40,
274         terabyte        => 2 ** 40,
275         P               => 2 ** 50,
276         PB              => 2 ** 50,
277         petabyte        => 2 ** 50,
278         E               => 2 ** 60,
279         EB              => 2 ** 60,
280         exabyte         => 2 ** 60,
281         Z               => 2 ** 70,
282         ZB              => 2 ** 70,
283         zettabyte       => 2 ** 70,
284         Y               => 2 ** 80,
285         YB              => 2 ** 80,
286         yottabyte       => 2 ** 80,
287         # ikiwiki, if you find you need larger data quantities, either modify
288         # yourself to add them, or travel back in time to 2008 and kill me.
289         #   -- Joey
290 ); #}}}
291
292 sub parsesize ($) { #{{{
293         my $size=shift;
294
295         no warnings;
296         my $base=$size+0; # force to number
297         use warnings;
298         foreach my $unit (sort keys %units) {
299                 if ($size=~/[0-9\s]\Q$unit\E$/i) {
300                         return $base * $units{$unit};
301                 }
302         }
303         return $base;
304 } #}}}
305
306 sub humansize ($) { #{{{
307         my $size=shift;
308
309         foreach my $unit (reverse sort { $units{$a} <=> $units{$b} || $b cmp $a } keys %units) {
310                 if ($size / $units{$unit} > 0.25) {
311                         return (int($size / $units{$unit} * 10)/10).$unit;
312                 }
313         }
314         return $size; # near zero, or negative
315 } #}}}
316
317 package IkiWiki::PageSpec;
318
319 sub match_maxsize ($$;@) { #{{{
320         shift;
321         my $maxsize=eval{IkiWiki::Plugin::attachment::parsesize(shift)};
322         if ($@) {
323                 return IkiWiki::FailReason->new("unable to parse maxsize (or number too large)");
324         }
325
326         my %params=@_;
327         if (! exists $params{file}) {
328                 return IkiWiki::FailReason->new("no file specified");
329         }
330
331         if (-s $params{file} > $maxsize) {
332                 return IkiWiki::FailReason->new("file too large (".(-s $params{file})." >  $maxsize)");
333         }
334         else {
335                 return IkiWiki::SuccessReason->new("file not too large");
336         }
337 } #}}}
338
339 sub match_minsize ($$;@) { #{{{
340         shift;
341         my $minsize=eval{IkiWiki::Plugin::attachment::parsesize(shift)};
342         if ($@) {
343                 return IkiWiki::FailReason->new("unable to parse minsize (or number too large)");
344         }
345
346         my %params=@_;
347         if (! exists $params{file}) {
348                 return IkiWiki::FailReason->new("no file specified");
349         }
350
351         if (-s $params{file} < $minsize) {
352                 return IkiWiki::FailReason->new("file too small");
353         }
354         else {
355                 return IkiWiki::SuccessReason->new("file not too small");
356         }
357 } #}}}
358
359 sub match_mimetype ($$;@) { #{{{
360         shift;
361         my $wanted=shift;
362
363         my %params=@_;
364         if (! exists $params{file}) {
365                 return IkiWiki::FailReason->new("no file specified");
366         }
367
368         # Use ::magic to get the mime type, the idea is to only trust
369         # data obtained by examining the actual file contents.
370         eval q{use File::MimeInfo::Magic};
371         if ($@) {
372                 return IkiWiki::FailReason->new("failed to load File::MimeInfo::Magic ($@); cannot check MIME type");
373         }
374         my $mimetype=File::MimeInfo::Magic::magic($params{file});
375         if (! defined $mimetype) {
376                 $mimetype="unknown";
377         }
378
379         my $regexp=IkiWiki::glob2re($wanted);
380         if ($mimetype!~/^$regexp$/i) {
381                 return IkiWiki::FailReason->new("file MIME type is $mimetype, not $wanted");
382         }
383         else {
384                 return IkiWiki::SuccessReason->new("file MIME type is $mimetype");
385         }
386 } #}}}
387
388 sub match_virusfree ($$;@) { #{{{
389         shift;
390         my $wanted=shift;
391
392         my %params=@_;
393         if (! exists $params{file}) {
394                 return IkiWiki::FailReason->new("no file specified");
395         }
396
397         if (! exists $IkiWiki::config{virus_checker} ||
398             ! length $IkiWiki::config{virus_checker}) {
399                 return IkiWiki::FailReason->new("no virus_checker configured");
400         }
401
402         # The file needs to be fed into the virus checker on stdin,
403         # because the file is not world-readable, and if clamdscan is
404         # used, clamd would fail to read it.
405         eval q{use IPC::Open2};
406         error($@) if $@;
407         open (IN, "<", $params{file}) || return IkiWiki::FailReason->new("failed to read file");
408         binmode(IN);
409         my $sigpipe=0;
410         $SIG{PIPE} = sub { $sigpipe=1 };
411         my $pid=open2(\*CHECKER_OUT, "<&IN", $IkiWiki::config{virus_checker}); 
412         my $reason=<CHECKER_OUT>;
413         chomp $reason;
414         1 while (<CHECKER_OUT>);
415         close(CHECKER_OUT);
416         waitpid $pid, 0;
417         $SIG{PIPE}="DEFAULT";
418         if ($sigpipe || $?) {
419                 if (! length $reason) {
420                         $reason="virus checker $IkiWiki::config{virus_checker}; failed with no output";
421                 }
422                 return IkiWiki::FailReason->new("file seems to contain a virus ($reason)");
423         }
424         else {
425                 return IkiWiki::SuccessReason->new("file seems virusfree ($reason)");
426         }
427 } #}}}
428
429 sub match_ispage ($$;@) { #{{{
430         my $filename=shift;
431
432         if (defined IkiWiki::pagetype($filename)) {
433                 return IkiWiki::SuccessReason->new("file is a wiki page");
434         }
435         else {
436                 return IkiWiki::FailReason->new("file is not a wiki page");
437         }
438 } #}}}
439
440 sub match_user ($$;@) { #{{{
441         shift;
442         my $user=shift;
443         my %params=@_;
444         
445         if (! exists $params{user}) {
446                 return IkiWiki::FailReason->new("no user specified");
447         }
448
449         if (defined $params{user} && lc $params{user} eq lc $user) {
450                 return IkiWiki::SuccessReason->new("user is $user");
451         }
452         elsif (! defined $params{user}) {
453                 return IkiWiki::FailReason->new("not logged in");
454         }
455         else {
456                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
457         }
458 } #}}}
459
460 sub match_ip ($$;@) { #{{{
461         shift;
462         my $ip=shift;
463         my %params=@_;
464         
465         if (! exists $params{ip}) {
466                 return IkiWiki::FailReason->new("no IP specified");
467         }
468
469         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
470                 return IkiWiki::SuccessReason->new("IP is $ip");
471         }
472         else {
473                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
474         }
475 } #}}}
476
477 1