]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/attachment.pm
a58f696ebf203c841e9e3c39a883c80886eddf74
[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 checkconfig () { #{{{
15         $config{cgi_disable_uploads}=0;
16 } #}}}
18 sub formbuilder_setup (@) { #{{{
19         my %params=@_;
20         my $form=$params{form};
21         my $q=$params{cgi};
23         if ($form->field("do") eq "edit") {
24                 $form->field(name => 'attachment', type => 'file');
25                 # These buttons are not put in the usual place, so
26                 # are not added to the normal formbuilder button list.
27                 $form->tmpl_param("field-upload" => '<input name="_submit" type="submit" value="Upload Attachment" />');
28                 $form->tmpl_param("field-link" => '<input name="_submit" type="submit" value="Insert Links" />');
30                 # Add the javascript from the toggle plugin;
31                 # the attachments interface uses it to toggle visibility.
32                 require IkiWiki::Plugin::toggle;
33                 $form->tmpl_param("javascript" => $IkiWiki::Plugin::toggle::javascript);
34                 # Start with the attachments interface toggled invisible,
35                 # but if it was used, keep it open.
36                 if ($form->submitted ne "Upload Attachment" &&
37                     ! length $q->param("attachment_select")) {
38                         $form->tmpl_param("attachments-class" => "toggleable");
39                 }
40                 else {
41                         $form->tmpl_param("attachments-class" => "toggleable-open");
42                 }
43         }
44         elsif ($form->title eq "preferences") {
45                 my $session=$params{session};
46                 my $user_name=$session->param("name");
48                 $form->field(name => "allowed_attachments", size => 50,
49                         fieldset => "admin",
50                         comment => "(".htmllink("", "", "ikiwiki/PageSpec", noimageinline => 1).")");
51                 if (! IkiWiki::is_admin($user_name)) {
52                         $form->field(name => "allowed_attachments", type => "hidden");
53                 }
54                 if (! $form->submitted) {
55                         $form->field(name => "allowed_attachments", force => 1,
56                                 value => IkiWiki::userinfo_get($user_name, "allowed_attachments"));
57                 }
58                 if ($form->submitted && $form->submitted eq 'Save Preferences') {
59                         if (defined $form->field("allowed_attachments")) {
60                                 IkiWiki::userinfo_set($user_name, "allowed_attachments",
61                                 $form->field("allowed_attachments")) ||
62                                         error("failed to set allowed_attachments");
63                         }
64                 }
65         }
66 } #}}}
68 sub formbuilder (@) { #{{{
69         my %params=@_;
70         my $form=$params{form};
71         my $q=$params{cgi};
73         return if $form->field("do") ne "edit";
75         my $filename=$q->param('attachment');
76         if (defined $filename && length $filename &&
77             ($form->submitted eq "Upload Attachment" || $form->submitted eq "Save Page")) {
78                 my $session=$params{session};
79                 
80                 # This is an (apparently undocumented) way to get the name
81                 # of the temp file that CGI writes the upload to.
82                 my $tempfile=$q->tmpFileName($filename);
83                 
84                 $filename=IkiWiki::titlepage(
85                         IkiWiki::possibly_foolish_untaint(
86                                 attachment_location($form->field('page')).
87                                 IkiWiki::basename($filename)));
88                 if (IkiWiki::file_pruned($filename, $config{srcdir})) {
89                         error(gettext("bad attachment filename"));
90                 }
91                 
92                 # Check that the user is allowed to edit a page with the
93                 # name of the attachment.
94                 IkiWiki::check_canedit($filename, $q, $session, 1);
95                 
96                 # Use a special pagespec to test that the attachment is valid.
97                 my $allowed=1;
98                 foreach my $admin (@{$config{adminuser}}) {
99                         my $allowed_attachments=IkiWiki::userinfo_get($admin, "allowed_attachments");
100                         if (defined $allowed_attachments &&
101                             length $allowed_attachments) {
102                                 $allowed=pagespec_match($filename,
103                                         $allowed_attachments,
104                                         file => $tempfile);
105                                 last if $allowed;
106                         }
107                 }
108                 if (! $allowed) {
109                         error(gettext("attachment rejected")." ($allowed)");
110                 }
112                 # Needed for fast_file_copy and for rendering below.
113                 require IkiWiki::Render;
115                 # Move the attachment into place.
116                 # Try to use a fast rename; fall back to copying.
117                 IkiWiki::prep_writefile($filename, $config{srcdir});
118                 unlink($config{srcdir}."/".$filename);
119                 if (rename($tempfile, $config{srcdir}."/".$filename)) {
120                         # The temp file has tight permissions; loosen up.
121                         chmod(0666 & ~umask, $config{srcdir}."/".$filename);
122                 }
123                 else {
124                         my $fh=$q->upload('attachment');
125                         if (! defined $fh || ! ref $fh) {
126                                 error("failed to get filehandle");
127                         }
128                         binmode($fh);
129                         writefile($filename, $config{srcdir}, undef, 1, sub {
130                                 IkiWiki::fast_file_copy($tempfile, $filename, $fh, @_);
131                         });
132                 }
134                 # Check the attachment in and trigger a wiki refresh.
135                 if ($config{rcs}) {
136                         IkiWiki::rcs_add($filename);
137                         IkiWiki::disable_commit_hook();
138                         IkiWiki::rcs_commit($filename, gettext("attachment upload"),
139                                 IkiWiki::rcs_prepedit($filename),
140                                 $session->param("name"), $ENV{REMOTE_ADDR});
141                         IkiWiki::enable_commit_hook();
142                         IkiWiki::rcs_update();
143                 }
144                 IkiWiki::refresh();
145                 IkiWiki::saveindex();
146         }
147         elsif ($form->submitted eq "Insert Links") {
148                 my $add="";
149                 foreach my $f ($q->param("attachment_select")) {
150                         $add.="[[$f]]\n";
151                 }
152                 $form->field(name => 'editcontent',
153                         value => $form->field('editcontent')."\n\n".$add,
154                         force => 1) if length $add;
155         }
156         
157         # Generate the attachment list only after having added any new
158         # attachments.
159         $form->tmpl_param("attachment_list" => [attachment_list($form->field('page'))]);
160 } # }}}
162 sub attachment_location ($) {
163         my $page=shift;
164         
165         # Put the attachment in a subdir of the page it's attached
166         # to, unless that page is an "index" page.
167         $page=~s/(^|\/)index//;
168         $page.="/" if length $page;
169         
170         return $page;
173 sub attachment_list ($) {
174         my $page=shift;
175         my $loc=attachment_location($page);
177         my @ret;
178         foreach my $f (values %pagesources) {
179                 if (! defined IkiWiki::pagetype($f) &&
180                     $f=~m/^\Q$loc\E[^\/]+$/ &&
181                     -e "$config{srcdir}/$f") {
182                         push @ret, {
183                                 "field-select" => '<input type="checkbox" name="attachment_select" value="'.$f.'">',
184                                 link => htmllink($page, $page, $f, noimageinline => 1),
185                                 size => humansize((stat(_))[7]),
186                                 mtime => displaytime($IkiWiki::pagemtime{$f}),
187                                 mtime_raw => $IkiWiki::pagemtime{$f},
188                         };
189                 }
190         }
192         # Sort newer attachments to the top of the list, so a newly-added
193         # attachment appears just before the form used to add it.
194         return sort { $b->{mtime_raw} <=> $a->{mtime_raw} || $a->{link} cmp $b->{link} } @ret;
197 my %units=(             # size in bytes
198         B               => 1,
199         byte            => 1,
200         KB              => 2 ** 10,
201         kilobyte        => 2 ** 10,
202         K               => 2 ** 10,
203         KB              => 2 ** 10,
204         kilobyte        => 2 ** 10,
205         M               => 2 ** 20,
206         MB              => 2 ** 20,
207         megabyte        => 2 ** 20,
208         G               => 2 ** 30,
209         GB              => 2 ** 30,
210         gigabyte        => 2 ** 30,
211         T               => 2 ** 40,
212         TB              => 2 ** 40,
213         terabyte        => 2 ** 40,
214         P               => 2 ** 50,
215         PB              => 2 ** 50,
216         petabyte        => 2 ** 50,
217         E               => 2 ** 60,
218         EB              => 2 ** 60,
219         exabyte         => 2 ** 60,
220         Z               => 2 ** 70,
221         ZB              => 2 ** 70,
222         zettabyte       => 2 ** 70,
223         Y               => 2 ** 80,
224         YB              => 2 ** 80,
225         yottabyte       => 2 ** 80,
226         # ikiwiki, if you find you need larger data quantities, either modify
227         # yourself to add them, or travel back in time to 2008 and kill me.
228         #   -- Joey
229 );
231 sub parsesize ($) { #{{{
232         my $size=shift;
234         no warnings;
235         my $base=$size+0; # force to number
236         use warnings;
237         foreach my $unit (sort keys %units) {
238                 if ($size=~/[0-9\s]\Q$unit\E$/i) {
239                         return $base * $units{$unit};
240                 }
241         }
242         return $base;
243 } #}}}
245 sub humansize ($) { #{{{
246         my $size=shift;
248         foreach my $unit (reverse sort { $units{$a} <=> $units{$b} || $b cmp $a } keys %units) {
249                 if ($size / $units{$unit} > 0.25) {
250                         return (int($size / $units{$unit} * 10)/10).$unit;
251                 }
252         }
253         return $size; # near zero, or negative
254 } #}}}
256 package IkiWiki::PageSpec;
258 sub match_maxsize ($$;@) { #{{{
259         shift;
260         my $maxsize=eval{IkiWiki::Plugin::attachment::parsesize(shift)};
261         if ($@) {
262                 return IkiWiki::FailReason->new("unable to parse maxsize (or number too large)");
263         }
265         my %params=@_;
266         if (! exists $params{file}) {
267                 return IkiWiki::FailReason->new("no file specified");
268         }
270         if (-s $params{file} > $maxsize) {
271                 return IkiWiki::FailReason->new("file too large (".(-s $params{file})." >  $maxsize)");
272         }
273         else {
274                 return IkiWiki::SuccessReason->new("file not too large");
275         }
276 } #}}}
278 sub match_minsize ($$;@) { #{{{
279         shift;
280         my $minsize=eval{IkiWiki::Plugin::attachment::parsesize(shift)};
281         if ($@) {
282                 return IkiWiki::FailReason->new("unable to parse minsize (or number too large)");
283         }
285         my %params=@_;
286         if (! exists $params{file}) {
287                 return IkiWiki::FailReason->new("no file specified");
288         }
290         if (-s $params{file} < $minsize) {
291                 return IkiWiki::FailReason->new("file too small");
292         }
293         else {
294                 return IkiWiki::SuccessReason->new("file not too small");
295         }
296 } #}}}
298 sub match_ispage ($$;@) { #{{{
299         my $filename=shift;
301         if (defined IkiWiki::pagetype($filename)) {
302                 return IkiWiki::SuccessReason->new("file is a wiki page");
303         }
304         else {
305                 return IkiWiki::FailReason->new("file is not a wiki page");
306         }
307 } #}}}