]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/attachment.pm
fixed previewing of attachments from holding area
[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 3.00;
8 sub import {
9         add_underlay("javascript");
10         hook(type => "getsetup", id => "attachment", call => \&getsetup);
11         hook(type => "checkconfig", id => "attachment", call => \&checkconfig);
12         hook(type => "formbuilder_setup", id => "attachment", call => \&formbuilder_setup);
13         hook(type => "formbuilder", id => "attachment", call => \&formbuilder);
14         IkiWiki::loadplugin("filecheck");
15 }
17 sub getsetup () {
18         return
19                 plugin => {
20                         safe => 1,
21                         rebuild => 0,
22                         section => "web",
23                 },
24                 allowed_attachments => {
25                         type => "pagespec",
26                         example => "virusfree() and mimetype(image/*) and maxsize(50kb)",
27                         description => "enhanced PageSpec specifying what attachments are allowed",
28                         link => "ikiwiki/PageSpec/attachment",
29                         safe => 1,
30                         rebuild => 0,
31                 },
32                 virus_checker => {
33                         type => "string",
34                         example => "clamdscan -",
35                         description => "virus checker program (reads STDIN, returns nonzero if virus found)",
36                         safe => 0, # executed
37                         rebuild => 0,
38                 },
39 }
41 sub check_canattach ($$;$) {
42         my $session=shift;
43         my $dest=shift; # where it's going to be put, under the srcdir
44         my $file=shift; # the path to the attachment currently
46         # Don't allow an attachment to be uploaded with the same name as an
47         # existing page.
48         if (exists $IkiWiki::pagesources{$dest} &&
49             $IkiWiki::pagesources{$dest} ne $dest) {
50                 error(sprintf(gettext("there is already a page named %s"), $dest));
51         }
53         # Use a special pagespec to test that the attachment is valid.
54         my $allowed=1;
55         if (defined $config{allowed_attachments} &&
56             length $config{allowed_attachments}) {
57                 $allowed=pagespec_match($dest,
58                         $config{allowed_attachments},
59                         file => $file,
60                         user => $session->param("name"),
61                         ip => $session->remote_addr(),
62                 );
63         }
65         if (! $allowed) {
66                 error(gettext("prohibited by allowed_attachments")." ($allowed)");
67         }
68         else {
69                 return 1;
70         }
71 }
73 sub checkconfig () {
74         $config{cgi_disable_uploads}=0;
75 }
77 sub formbuilder_setup (@) {
78         my %params=@_;
79         my $form=$params{form};
80         my $q=$params{cgi};
82         if (defined $form->field("do") && ($form->field("do") eq "edit" ||
83             $form->field("do") eq "create")) {
84                 # Add attachment field, set type to multipart.
85                 $form->enctype(&CGI::MULTIPART);
86                 $form->field(name => 'attachment', type => 'file');
87                 # These buttons are not put in the usual place, so
88                 # are not added to the normal formbuilder button list.
89                 $form->tmpl_param("field-upload" => '<input name="_submit" type="submit" value="Upload Attachment" />');
90                 $form->tmpl_param("field-link" => '<input name="_submit" type="submit" value="Insert Links" />');
92                 # Add the toggle javascript; the attachments interface uses
93                 # it to toggle visibility.
94                 require IkiWiki::Plugin::toggle;
95                 $form->tmpl_param("javascript" => IkiWiki::Plugin::toggle::include_javascript($params{page}));
96                 # Start with the attachments interface toggled invisible,
97                 # but if it was used, keep it open.
98                 if ($form->submitted ne "Upload Attachment" &&
99                     (! defined $q->param("attachment_select") ||
100                     ! length $q->param("attachment_select"))) {
101                         $form->tmpl_param("attachments-class" => "toggleable");
102                 }
103                 else {
104                         $form->tmpl_param("attachments-class" => "toggleable-open");
105                 }
106                 
107                 # Save attachments in holding area before previewing so
108                 # they can be seen in the preview.
109                 if ($form->submitted eq "Preview") {
110                         attachments_save($form, $params{session});
111                 }
112         }
115 sub formbuilder (@) {
116         my %params=@_;
117         my $form=$params{form};
118         my $q=$params{cgi};
120         return if ! defined $form->field("do") || ($form->field("do") ne "edit" && $form->field("do") ne "create") ;
122         my $filename=Encode::decode_utf8($q->param('attachment'));
123         if (defined $filename && length $filename &&
124             ($form->submitted eq "Upload Attachment" || $form->submitted eq "Save Page")) {
125                 attachment_store($filename, $form, $q, $params{session});
126         }
127         if ($form->submitted eq "Save Page") {
128                 attachments_save($form, $params{session});
129         }
131         if ($form->submitted eq "Insert Links") {
132                 my $page=quotemeta(Encode::decode_utf8($q->param("page")));
133                 my $add="";
134                 foreach my $f ($q->param("attachment_select")) {
135                         $f=Encode::decode_utf8($f);
136                         $f=~s/^$page\///;
137                         if (IkiWiki::isinlinableimage($f) &&
138                             UNIVERSAL::can("IkiWiki::Plugin::img", "import")) {
139                                 $add.='[[!img '.$f.' align="right" size="" alt=""]]';
140                         }
141                         else {
142                                 $add.="[[$f]]";
143                         }
144                         $add.="\n";
145                 }
146                 $form->field(name => 'editcontent',
147                         value => $form->field('editcontent')."\n\n".$add,
148                         force => 1) if length $add;
149         }
150         
151         # Generate the attachment list only after having added any new
152         # attachments.
153         $form->tmpl_param("attachment_list" => [attachment_list($form->field('page'))]);
156 sub attachment_holding_dir {
157         my $page=shift;
159         return $config{wikistatedir}."/attachments/".
160                 IkiWiki::possibly_foolish_untaint(linkpage($page));
163 # Stores the attachment in a holding area, not yet in the wiki proper.
164 sub attachment_store {
165         my $filename=shift;
166         my $form=shift;
167         my $q=shift;
168         my $session=shift;
169         
170         # This is an (apparently undocumented) way to get the name
171         # of the temp file that CGI writes the upload to.
172         my $tempfile=$q->tmpFileName($filename);
173         if (! defined $tempfile || ! length $tempfile) {
174                 # perl 5.8 needs an alternative, awful method
175                 if ($q =~ /HASH/ && exists $q->{'.tmpfiles'}) {
176                         foreach my $key (keys(%{$q->{'.tmpfiles'}})) {
177                                 $tempfile=$q->tmpFileName(\$key);
178                                 last if defined $tempfile && length $tempfile;
179                         }
180                 }
181                 if (! defined $tempfile || ! length $tempfile) {
182                         error("CGI::tmpFileName failed to return the uploaded file name");
183                 }
184         }
186         $filename=IkiWiki::basename($filename);
187         $filename=~s/.*\\+(.+)/$1/; # hello, windows
188         $filename=IkiWiki::possibly_foolish_untaint(linkpage($filename));
189         
190         # Check that the user is allowed to edit the attachment.
191         my $final_filename=
192                 linkpage(IkiWiki::possibly_foolish_untaint(
193                         attachment_location($form->field('page')))).
194                 $filename;
195         if (IkiWiki::file_pruned($final_filename)) {
196                 error(gettext("bad attachment filename"));
197         }
198         IkiWiki::check_canedit($final_filename, $q, $session);
199         # And that the attachment itself is acceptable.
200         check_canattach($session, $final_filename, $tempfile);
202         # Move the attachment into holding directory.
203         # Try to use a fast rename; fall back to copying.
204         my $dest=attachment_holding_dir($form->field('page'));
205         IkiWiki::prep_writefile($filename, $dest);
206         unlink($dest."/".$filename);
207         if (rename($tempfile, $dest."/".$filename)) {
208                 # The temp file has tight permissions; loosen up.
209                 chmod(0666 & ~umask, $dest."/".$filename);
210         }
211         else {
212                 my $fh=$q->upload('attachment');
213                 if (! defined $fh || ! ref $fh) {
214                         # needed by old CGI versions
215                         $fh=$q->param('attachment');
216                         if (! defined $fh || ! ref $fh) {
217                                 # even that doesn't always work,
218                                 # fall back to opening the tempfile
219                                 $fh=undef;
220                                 open($fh, "<", $tempfile) || error("failed to open \"$tempfile\": $!");
221                         }
222                 }
223                 binmode($fh);
224                 # Needed for fast_file_copy.
225                 require IkiWiki::Render;
226                 writefile($filename, $dest, undef, 1, sub {
227                         IkiWiki::fast_file_copy($tempfile, $filename, $fh, @_);
228                 });
229         }
232 # Save all stored attachments for a page.
233 sub attachments_save {
234         my $form=shift;
235         my $session=shift;
237         # Move attachments out of holding directory.
238         my @attachments;
239         my $dir=attachment_holding_dir($form->field('page'));
240         foreach my $filename (glob("$dir/*")) {
241                 next unless -f $filename;
242                 my $dest=$config{srcdir}."/".
243                         linkpage(IkiWiki::possibly_foolish_untaint(
244                                 attachment_location($form->field('page')))).
245                         IkiWiki::basename($filename);
246                 unlink($dest);
247                 rename($filename, $dest);
248                 push @attachments, $dest;
249         }
250         return unless @attachments;
251         rmdir($dir);
253         # Check the attachments in and trigger a wiki refresh.
254         if ($config{rcs}) {
255                 IkiWiki::rcs_add($_) foreach @attachments;
256                 IkiWiki::disable_commit_hook();
257                 IkiWiki::rcs_commit_staged(
258                         message => gettext("attachment upload"),
259                         session => $session,
260                 );
261                 IkiWiki::enable_commit_hook();
262                 IkiWiki::rcs_update();
263         }
264         IkiWiki::refresh();
265         IkiWiki::saveindex();
268 sub attachment_location ($) {
269         my $page=shift;
270         
271         # Put the attachment in a subdir of the page it's attached
272         # to, unless that page is an "index" page.
273         $page=~s/(^|\/)index//;
274         $page.="/" if length $page;
275         
276         return $page;
279 sub attachment_list ($) {
280         my $page=shift;
281         my $loc=attachment_location($page);
283         # attachments already in the wiki
284         my %attachments;
285         foreach my $f (values %pagesources) {
286                 if (! defined pagetype($f) &&
287                     $f=~m/^\Q$loc\E[^\/]+$/) {
288                         $attachments{$f}={
289                                 "field-select" => '<input type="checkbox" name="attachment_select" value="'.$f.'" />',
290                                 link => htmllink($page, $page, $f, noimageinline => 1),
291                                 size => IkiWiki::Plugin::filecheck::humansize((stat($f))[7]),
292                                 mtime => displaytime($IkiWiki::pagemtime{$f}),
293                                 mtime_raw => $IkiWiki::pagemtime{$f},
294                         };
295                 }
296         }
297         
298         # attachments in holding directory
299         my $dir=attachment_holding_dir($page);
300         my $heldmsg=gettext("this attachment is not yet saved");
301         foreach my $file (glob("$dir/*")) {
302                 my $mtime=(stat($file))[9];
303                 my $f=IkiWiki::basename($file);
304                 $attachments{$f}={
305                         "field-select" => '<input type="checkbox" name="attachment_select" value="'.$f.'" />',
306                         link => "<span title=\"$heldmsg\">$f</span>",
307                         size => IkiWiki::Plugin::filecheck::humansize((stat($file))[7]),
308                         mtime => displaytime($mtime),
309                         mtime_raw => $mtime,
310                 }
311         }
313         # Sort newer attachments to the top of the list, so a newly-added
314         # attachment appears just before the form used to add it.
315         return sort { $b->{mtime_raw} <=> $a->{mtime_raw} || $a->{link} cmp $b->{link} }
316                 values %attachments;