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