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