]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/attachment.pm
f4bfbe98f4cc3eb63f313c7bf5d39c39eb4b2b26
[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         }
109 sub formbuilder (@) {
110         my %params=@_;
111         my $form=$params{form};
112         my $q=$params{cgi};
114         return if ! defined $form->field("do") || ($form->field("do") ne "edit" && $form->field("do") ne "create") ;
116         my $filename=Encode::decode_utf8($q->param('attachment'));
117         if (defined $filename && length $filename &&
118             ($form->submitted eq "Upload Attachment" || $form->submitted eq "Save Page")) {
119                 attachment_store($filename, $form, $q, $params{session});
120         }
121         if ($form->submitted eq "Save Page") {
122                 attachments_save($form, $params{session});
123         }
125         if ($form->submitted eq "Insert Links") {
126                 my $page=quotemeta(Encode::decode_utf8($q->param("page")));
127                 my $add="";
128                 foreach my $f ($q->param("attachment_select")) {
129                         $f=Encode::decode_utf8($f);
130                         $f=~s/^$page\///;
131                         if (IkiWiki::isinlinableimage($f) &&
132                             UNIVERSAL::can("IkiWiki::Plugin::img", "import")) {
133                                 $add.='[[!img '.$f.' align="right" size="" alt=""]]';
134                         }
135                         else {
136                                 $add.="[[$f]]";
137                         }
138                         $add.="\n";
139                 }
140                 $form->field(name => 'editcontent',
141                         value => $form->field('editcontent')."\n\n".$add,
142                         force => 1) if length $add;
143         }
144         
145         # Generate the attachment list only after having added any new
146         # attachments.
147         $form->tmpl_param("attachment_list" => [attachment_list($form->field('page'))]);
150 sub attachment_holding_dir {
151         my $page=shift;
153         return $config{wikistatedir}."/attachments/".
154                 IkiWiki::possibly_foolish_untaint(linkpage($page));
157 # Stores the attachment in a holding area, not yet in the wiki proper.
158 sub attachment_store {
159         my $filename=shift;
160         my $form=shift;
161         my $q=shift;
162         my $session=shift;
163         
164         # This is an (apparently undocumented) way to get the name
165         # of the temp file that CGI writes the upload to.
166         my $tempfile=$q->tmpFileName($filename);
167         if (! defined $tempfile || ! length $tempfile) {
168                 # perl 5.8 needs an alternative, awful method
169                 if ($q =~ /HASH/ && exists $q->{'.tmpfiles'}) {
170                         foreach my $key (keys(%{$q->{'.tmpfiles'}})) {
171                                 $tempfile=$q->tmpFileName(\$key);
172                                 last if defined $tempfile && length $tempfile;
173                         }
174                 }
175                 if (! defined $tempfile || ! length $tempfile) {
176                         error("CGI::tmpFileName failed to return the uploaded file name");
177                 }
178         }
180         $filename=IkiWiki::basename($filename);
181         $filename=~s/.*\\+(.+)/$1/; # hello, windows
182         $filename=IkiWiki::possibly_foolish_untaint(linkpage($filename));
183         
184         # Check that the user is allowed to edit the attachment.
185         my $final_filename=
186                 linkpage(IkiWiki::possibly_foolish_untaint(
187                         attachment_location($form->field('page')))).
188                 $filename;
189         if (IkiWiki::file_pruned($final_filename)) {
190                 error(gettext("bad attachment filename"));
191         }
192         IkiWiki::check_canedit($final_filename, $q, $session);
193         # And that the attachment itself is acceptable.
194         check_canattach($session, $final_filename, $tempfile);
196         # Move the attachment into holding directory.
197         # Try to use a fast rename; fall back to copying.
198         my $dest=attachment_holding_dir($form->field('page'));
199         IkiWiki::prep_writefile($filename, $dest);
200         unlink($dest."/".$filename);
201         if (rename($tempfile, $dest."/".$filename)) {
202                 # The temp file has tight permissions; loosen up.
203                 chmod(0666 & ~umask, $dest."/".$filename);
204         }
205         else {
206                 my $fh=$q->upload('attachment');
207                 if (! defined $fh || ! ref $fh) {
208                         # needed by old CGI versions
209                         $fh=$q->param('attachment');
210                         if (! defined $fh || ! ref $fh) {
211                                 # even that doesn't always work,
212                                 # fall back to opening the tempfile
213                                 $fh=undef;
214                                 open($fh, "<", $tempfile) || error("failed to open \"$tempfile\": $!");
215                         }
216                 }
217                 binmode($fh);
218                 # Needed for fast_file_copy.
219                 require IkiWiki::Render;
220                 writefile($filename, $dest, undef, 1, sub {
221                         IkiWiki::fast_file_copy($tempfile, $filename, $fh, @_);
222                 });
223         }
226 # Save all stored attachments for a page.
227 sub attachments_save {
228         my $form=shift;
229         my $session=shift;
231         # Move attachments out of holding directory.
232         my @attachments;
233         my $dir=attachment_holding_dir($form->field('page'));
234         foreach my $filename (glob("$dir/*")) {
235                 next unless -f $filename;
236                 my $dest=$config{srcdir}."/".
237                         linkpage(IkiWiki::possibly_foolish_untaint(
238                                 attachment_location($form->field('page')))).
239                         $filename;
240                 unlink($dest);
241                 rename($filename, $dest);
242                 push @attachments, $dest;
243         }
244         return unless @attachments;
245         rmdir($dir);
247         # Check the attachments in and trigger a wiki refresh.
248         if ($config{rcs}) {
249                 IkiWiki::rcs_add($_) foreach @attachments;
250                 IkiWiki::disable_commit_hook();
251                 IkiWiki::rcs_commit_staged(
252                         message => gettext("attachment upload"),
253                         session => $session,
254                 );
255                 IkiWiki::enable_commit_hook();
256                 IkiWiki::rcs_update();
257         }
258         IkiWiki::refresh();
259         IkiWiki::saveindex();
262 sub attachment_location ($) {
263         my $page=shift;
264         
265         # Put the attachment in a subdir of the page it's attached
266         # to, unless that page is an "index" page.
267         $page=~s/(^|\/)index//;
268         $page.="/" if length $page;
269         
270         return $page;
273 sub attachment_list ($) {
274         my $page=shift;
275         my $loc=attachment_location($page);
277         my @ret;
278         foreach my $f (values %pagesources) {
279                 if (! defined pagetype($f) &&
280                     $f=~m/^\Q$loc\E[^\/]+$/) {
281                         push @ret, {
282                                 "field-select" => '<input type="checkbox" name="attachment_select" value="'.$f.'" />',
283                                 link => htmllink($page, $page, $f, noimageinline => 1),
284                                 size => IkiWiki::Plugin::filecheck::humansize((stat($f))[7]),
285                                 mtime => displaytime($IkiWiki::pagemtime{$f}),
286                                 mtime_raw => $IkiWiki::pagemtime{$f},
287                         };
288                 }
289         }
291         # Sort newer attachments to the top of the list, so a newly-added
292         # attachment appears just before the form used to add it.
293         return sort { $b->{mtime_raw} <=> $a->{mtime_raw} || $a->{link} cmp $b->{link} } @ret;